The code for the string formatting sequence will use the asterisk field width specifier to format a table containing the price of the fruit, with the total width of the table entered by the user. Because information is provided by the user, the field width cannot be hard-coded in the conversion descriptor. The field width can be read from the conversion tuple using the asterisk operator.
#print a formatted price list with a given widthWidth=input ('Please enter width:') Price_width=10Item_width=width-Price_widthheader_format='%-*s%*s'format='%-*s%*.2f'Print '='*widthPrintHeader_format% (Item_width,'Item', Price_width,' Price')Print '_'*widthPrintFormat% (Item_width,'Apples', price_width,0.4)PrintFormat% (Item_width,'Pears', price_width,0.5)PrintFormat% (Item_width,'cantaloupes', price_width,1.92)PrintFormat% (Item_width,'dried apricots (oz.)', price_width,8)PrintFormat% (Item_width,'Prunes (4 lbs.)', price_width,12)Print '='*width
The following is an example of a program run:
Please enter width:35
===================================
Item Price
___________________________________
Apples 0.40
Pears 0.50
Cantaloupes 1.92
Dried apricots (8.00 oz.)
Prunes (4 lbs.) 12.00
===================================
Dictionary examples
#Simple Database#use a name as a dictionary of keys. Each person is represented by another dictionary whose key ' phone ' and ' addr ' represent their phone number and address respectively .people={ 'Alice':{ 'Phone':'2341', 'Addr':'Foo Drive' }, 'Beth':{ 'Phone':'9102', 'Addr':'Bar Street' }, 'Cecil':{ 'Phone':'3158', 'Addr':'Baz Avenue' }}#descriptive labels for phone numbers and addresses are used when printing outputlabels={ 'Phone':'Phone number', 'Addr':'Address'}name= Raw_input ('Name:')#looking for a phone number or address? Use the correct key:Request = Raw_input ('Phone Number (p) or address (a)?')#Use the correct key:ifRequest = ='P': key='Phone'ifRequest = ='a': key='Addr'#If the name is a valid key in the dictionary, the information is printed:ifNameinchPeople:Print "%s '%s ' is%s."%(name, Labels[key], People[name][key])
The following is an example of a program run:
Name:beth
Phone number (p) or address (a)? p
Beth ' s phone number is 9102.
Python string formatting sequence example and dictionary example