'''strings4.py Jeff Ondich, 2 April 2009 This sample program will introduce you to formatted strings using Python's "interpolation" operator. See http://docs.python.org/library/stdtypes.html#string-formatting-operations 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 = raw_input('What is your name? ') print 'Hi', userName, '. It is a pleasure to meet you.' print # Let's fix that problem. The print statement below uses the # "interpolation operator" (the percent sign) to insert one # string (the user's name, stored in the variable userName) into # the longer string 'Hi...'. # # -- Where does the interpolated string userName get inserted # into the larger string? # -- What do you think the s in %s stands for? userName = raw_input('What is your name? ') print 'Hi %s. It is a pleasure to meet you.' % userName print # You can interpolate more than one thing, and more than one kind # of thing, into a string. # # -- Note that you need parentheses and a comma to interpolate # more than one object into a string. # -- What do you think the d in %d stands for? userName = raw_input('What is your name? ') numberString = raw_input('What is your favorite number? ') number = int(numberString) print 'Hi %s. Astonishingly, %d is my favorite number, too!' % (userName, number) print # You can make pretty columns with some special features of # formatted strings. # # Try the following code. Then look here: # # http://docs.python.org/library/stdtypes.html#string-formatting-operations # # or here: # # http://infohost.nmt.edu/tcc/help/pubs/lang/pytut/str-format.html # # 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 '%-15s%f' % (people[k], hourlyWages[k])