字符串格式化示例

《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,即保留小数点后两位。

 

转载于:https://www.cnblogs.com/my_captain/p/8681095.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值