字符串格式化示例

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

 


__EOF__

本文作者cnhkzyy
本文链接https://www.cnblogs.com/my_captain/p/8681095.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   cnhkzyy  阅读(336)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示