第3章 使用字符串

代码清单3-1 字符串格式设置示例

# Print a formatted price list with a given width

width = int(input('Please enter width: '))

price_width = 10
item_width  = width - price_width

header_fmt = '{{:{}}}{{:>{}}}'.format(item_width, price_width)
fmt        = '{{:{}}}{{:>{}.2f}}'.format(item_width, price_width)

print('=' * width)

print(header_fmt.format('Item', 'Price'))

print('-' * width)

print(fmt.format('Apples', 0.4))
print(fmt.format('Pears', 0.5))
print(fmt.format('Cantaloupes', 1.92))
print(fmt.format('Dried Apricots (16 oz.)', 8))
print(fmt.format('Prunes (4 lbs.)', 12))

print('=' * width)

运行结果如下:

Please enter width: 35
===================================
Item                          Price
-----------------------------------
Apples                         0.40
Pears                          0.50
Cantaloupes                    1.92
Dried Apricots (16 oz.)        8.00
Prunes (4 lbs.)               12.00
===================================
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • CREATE TABLE test (id int(11) NOT NULL AUTO_INCREMENT,aid...
    寂寞旅行阅读 1,859评论 1 1
  • 查看第9列有哪些注释信息: awk 'BEGIN{FS=OFS="\t"} {split($9, a, ";");...
    生信圈阅读 3,520评论 0 0
  • 1.file,n.文件;v.保存文件 [faɪl] 2.command,n.命令,指令 [kəˈmænd] 3.u...
    巢峰阅读 2,915评论 0 0
  • 1.SurfaceView详解 2.双缓冲技术 3.如何去使用SurfaceView # 二、自定义view ##...
    ab0758b97428阅读 1,886评论 0 0
  • 首先配置反向代理前已经要把之前配置过的伪静态删除掉,不然保存的时候报错以下是反向代理的完整配置,请注意其中的端口号...
    黑凤梨_be60阅读 1,126评论 0 0

友情链接更多精彩内容