3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) [Clang 6.0 (clang-600.0.57)] Python Type "help", "copyright", "credits" or "license" for more information. # String formatting # So far, when we want to put different strings together, we usually # concatenate them using + s1 = 'This course is' s2 = 'CSC120' s1 + s2 'This course isCSC120' # Annoying: we forget the space s = s1 + ' ' + s2 s 'This course is CSC120' # what if we also want a period at the end? s = s1 + ' ' + s2 + '.' s 'This course is CSC120.' # what if we want to add another part to the string? s3 = "and it's the best!" s = s1 + ' ' + s2 + ' ' + s3'.' Traceback (most recent call last): Python Shell, prompt 15, line 1 Syntax Error: invalid syntax: , line 1, pos 31 s = s1 + ' ' + s2 + ' ' + s3 + '.' s "This course is CSC120 and it's the best!." # The point is, this doesn't seem very efficient # and there has to be a better way # String Formatting # Lets us define the constant parts of a string and then the # parts the might change s1 'This course is' s2 'CSC120' # s1 contains the constant part # write out the constant part, and indicate the variable part with # curcly brackets s = 'This course is {}' # use the str.format() method to add the variable part s.format('CSC120') 'This course is CSC120' # The variable part is inserted in place of the curly brackets # The spaces are part of the constant portion of the string # adding a period is much easier as well: s = 'This course is {}.' s.format('CSC120') 'This course is CSC120.' # you can also do this all in one line with the literal 'This course is {}.'.format('CSC120') 'This course is CSC120.' # What about multiple variable parts? # Just add more curly brackets: "This course is {} and it's the {}.".format('CSC120', 'the best!') "This course is CSC120 and it's the the best!." "This course is {} and it's {}.".format('CSC120', 'the best!') "This course is CSC120 and it's the best!." # curly brackets are filled in from left to right in the # same order as the arguments to format() # You can also specify the order in the curly brackets "This course is {0} and it's {1}.".format('CSC120', 'the best!') "This course is CSC120 and it's the best!." "This course is {1} and it's {0}.".format('CSC120', 'the best!') "This course is the best! and it's CSC120." "This course is {0} and it's {1}. I love {0}.".format('CSC120', 'the best!') "This course is CSC120 and it's the best!. I love CSC120." # Always use this for putting strings together! s = 'This course is {}.' s.format('CSC120') 'This course is CSC120.' s 'This course is {}.' s = 'different string' s 'different string'