'''strings4.py Jed Yang, 2016-09-21 Adapted to Python 3 from a program written by Jeff Ondich, 2 April 2009 This sample program will introduce you to formatted strings using Python 3 str.format() method. See https://docs.python.org/3/library/string.html#formatstrings for more details. ''' # Recall this code from way back in strings0.py? There is a problem # with this code--it puts a space between your name and the period. userName = input('What is your name? ') print('Hi', userName, '. It is a pleasure to meet you.') print() # We already fixed it in two ways. Let us do it a third way. # The print statement below uses the str.format() method to insert one string # (the user's name, stored in the variable userName) into the longer string # 'Hi...'. # # -- Where does the string userName get inserted into the larger string? userName = input('What is your name? ') print('Hi {0}. It is a pleasure to meet you.'.format(userName)) print() # You can insert more than one thing, and more than one kind of thing, into a # string. # # -- What do you think the numbers inside curly braces {.} stand for? # -- If you swap {0} and {1}, can you make other changes so the output stays # the same as before? userName = input('What is your name? ') numberString = input('What is your favorite number? ') number = int(numberString) print('Hi {0}. Astonishingly, {1} is my favorite number, too!'.format(userName, number)) print() # You can make pretty columns with some special features of # formatted strings. # # Try the following code. Then look here: # # https://docs.python.org/3/library/string.html#formatstrings # # to see if you can figure out a way to force the hourly wages to be # right-justified with exactly two digits beyond the decimal point. people = ['Alice', 'Bob', 'Chrysanthemum', 'Donald'] hourlyWages = [15.456, 6.8, 254.25, 20] for k in range(len(people)): print('{0:15}{1:f}'.format(people[k], hourlyWages[k]))