python 基础教程里有一段字符串格式化示例:
- # coding=utf-8
- # 使用指定的宽度打印格式化后的价格列表
- width = input(Please enter with:)
- 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, Dried Apricots (16 oz.), price_width, 8)
- print format % (item_width, Prunes (4 lbs), price_width, 12)
- print = * width
运行效果如下:
- Please enter with: 35
- ===================================
- Item Price
- -----------------------------------
- Apples 0.40
- Pears 0.50
- Cantaloupes 1.92
- Dried Apricots (16 oz.) 8.00
- Prunes (4 lbs) 12.00
- ===================================
- Process finished with exit code 0
有几点值得考虑:
1. 用 * 作为字符的宽度 (或精度), 它的值从元组中读取;
2. header_format 的格式 %-25s%10s,- 代表左对齐, 那么 Item 字段所占的宽度为 25 并且左对齐, Price 字段所占宽度为 10 并且右对齐;
3. format 的格式为 %-25s%10.2f, 比如 Apples 字段所占的宽度为 25 并且左对齐, 0.4 字段所占宽度为 10 并且右对齐, 并且字段精度为 2, 即保留小数点后两位
来源: http://www.bubuko.com/infodetail-2544894.html