首页 > 代码库 > Beginning Python From Novice to Professional (4) - 字符串格式示例

Beginning Python From Novice to Professional (4) - 字符串格式示例

$ gedit price.py

#!/usr/bin/env python
width = input('Please enter width: ')
price_width = 10
item_width = width - price_width
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, 'Apricots',price_width,8)
print format % (item_width, 'Prunes',price_width,12)
print '=' * width
$ python price.py
Please enter width: 35
===================================
Item                          Price
-----------------------------------
Apples                         0.40
Pears                          0.50
Cantaloupes                    1.92
Apricots                       8.00
Prunes                        12.00
===================================
减号(-)用来左对齐数值

星号(*)表示精度从元组参数中读出

Beginning Python From Novice to Professional (4) - 字符串格式示例