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

$ gedit price.py

#!/usr/bin/env python
width = input('Please enter  ')
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  35
===================================
Item                          Price
-----------------------------------
Apples                         0.40
Pears                          0.50
Cantaloupes                    1.92
Apricots                       8.00
Prunes                        12.00
===================================
减号(-)用来左对齐数值

星号(*)分辨率从表达元组读取参数

版权声明:本文博客原创文章,博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/hrhguanli/p/4634134.html