Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # All the Ways to Print
- # the print() function and basic string object manipulation
- # print() with one argument
- print("Simple, one argument print call.")
- print() # or none, just for a line return
- # print() with multiple arguments
- print("Hello.", "I'm", "Johnny", "Cash.")
- # hidden keyword arguments: end and sep
- print("Hello.", "I'm", "Johnny", "Cash", ".", sep="--", end="") # overrode sep=" " and end="\n" defaults
- print('Next line? No.')
- # ways we build up larger strings
- # CONCATENATION + # easy to understand, also easy to mess up
- x ="Sue"
- print("My name is " + x + ". How do you do?") # if x wasn't a string, I'd recast it str(x)
- myString = "My name is " + x + ". How do you do?"
- # data conversion specifiers or "string modulo" %s %f %d
- print("I bet there's rich folks %s and in a fancy %s." % ("eating", "dining car"))
- # THE BEST WAY: string class .format() method
- print("They're probably drinking {} and smoking big {}!".format("coffee", "CIGARS"))
- phone = 5553337878
- phone = str(phone) # "5553337878"
- myString = "({}){}-{}".format(phone[0:3], phone[3:6], phone[6:])
- print(myString)
- myList = ["Gilligan", "Scooby", "Agent Scully", "Fonzie"]
- print(myList) # that's a list with [ ]
- for item in myList:
- if myList[-1] == item:
- print(item)
- else:
- print(item, end=", ")
- # for item in myList:
- # print(item, sep=",", end=" ") # doesn't work here, no sep b/c each call to print() has 1 arg only
- # print(dir(str)) # to see methods and properties of a type
- # help(str) # to see full help doc on type
- # help(str.format) # to see help on just one method
- # myString.method() is the usual syntax, but with .join() the separator string is what you start with...
- print(", ".join(myList))
- # help(str.join)
- myTuple = ("Gilligan", "Castaway002", "red", "crew")
- print(", ".join(myTuple))
- import random
- help(random.choice)
- import math
- # math.e or math.pi
- print(math.e)
- # string modulo/data conversion specifier
- # 5 decimal places for a float --> %.5f
- print("math.e to 5 places is %.5f" % math.e)
- # 5 decimal places for .format() --> :.5f
- print("math.e to 5 places is {:.5f}".format(math.e))
- # Question: "Can you use string modulo and string .format() together
- # Answer: No reason to, as you'd normally pick one OR the other. But you could...
- # ... ponders stringly
- # someVar = "pl{}".format("aces")
- print("Pi to %d %s" % (5, "pl{}".format("aces")+"."))
- # even better:
- print("Pi to %d %s is %.5f%s" % (5, "pl{}".format("ac")+"es", math.pi, ".")) # inelegant, but it works!
- # This has been a weird thought experiment in using string .format(), string modulo, and concatenation at the same time
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement