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

来源:互联网 发布:中日友好靠韩国 知乎 编辑:程序博客网 时间:2022/08/16 18:46

$ gedit price.py

#!/usr/bin/env pythonwidth = input('Please enter width: ')price_width = 10item_width = width - price_widthheader_format = '%-*s%*s'format        = '%-*s%*.2f'print '=' * widthprint header_format % (item_width, 'Item', price_width, 'Price')print '-' * widthprint 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.40Pears                          0.50Cantaloupes                    1.92Apricots                       8.00Prunes                        12.00===================================
减号(-)用来左对齐数值

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

1 0