新手求助 中文字符串对齐问题

2013-10-10 15:37:11 +08:00
 yundanfengqing
代码如下
#-*-coding:gbk-*-
width = input('请输入宽度:')

price_width = 10
item_width = width - price_width

header_format = '%-*s%*s'
format = '%-*s%*.2f'

print '=' * width

print header_format %(item_width,'项目',price_width,'价格')

print '-' * width

print format %(item_width,'苹果',price_width,0.40)
print format %(item_width,'鸭梨',price_width,0.50)
print format %(item_width,'哈密瓜',price_width,1.92)
print format %(item_width,'干杏仁',price_width,8)
print format %(item_width,'西梅干干干',price_width,12)

print '=' * width

显示如下

为什么后面对不齐呢
5742 次点击
所在节点    Python
3 条回复
spoony
2013-10-10 15:48:07 +08:00
西梅干干干
貌似干的越多越对不齐
vibbow
2013-10-10 17:29:10 +08:00
用等宽字符啊亲
phyng
2013-10-11 12:19:01 +08:00
终于弄明白了orz,2楼正解
简单解释就是:中文字符在字符占用上相当于两个英文字符,但是字体设计上,一般一个中文字符的宽度不会等于两个英文字符的宽度,所以打印出来的效果有偏差,但是等宽字符一个中文字体的宽度刚好等于两个英文字符宽度,所以正常:

非等宽字体比如我用的Yahei Console字体就是这样:

注意观察一个中文字符的宽度不等于两个英文字符。
另外,format = '%-*s%*.2f',这种格式化是比较旧的Python版本了(http://docs.python.org/release/2.5.2/lib/typesseq-strings.html),2.7及以后渐渐抛弃这种语法。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/85108

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX