Use tuple to provide value for string format

Format with tuple value

The following code shows how to use value in tuple to do the formatting.


width = 40# from   w  ww .  j av a  2 s .  c o  m
price_width = 10 
item_width = 30

header_format = '%-*s%*s' 
format       = '%-*s%*.2f' 

print '=' * width 
print header_format % (item_width, 'Item', price_width, 'Price') 
print '-' * width 

print format % (item_width, 'Apples', price_width, 0.4) 
print format % (item_width, 'Pears', price_width, 0.5) 
print format % (item_width, 'Cantaloupes', price_width, 1.92) 
print format % (item_width, 'Dried Apricots (16 oz.)', price_width, 8) 
print format % (item_width, 'Prunes (4 lbs.)', price_width, 12) 

print '=' * width 

The code above generates the following result.





















Home »
  Python »
    Data Types »




Data Types
String
String Format
Tuple
List
Set
Dictionary