Python UTF-8,如何对齐打印输出 [英] Python utf-8, howto align printout
本文介绍了Python UTF-8,如何对齐打印输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组,其中包含日本字符以及正常"字符. 如何对齐这些打印件?
I have a array containing japanese caracters as well as "normal". How do I align the printout of these?
#!/usr/bin/python
# coding=utf-8
a1=['する', 'します', 'trazan', 'した', 'しました']
a2=['dipsy', 'laa-laa', 'banarne', 'po', 'tinky winky']
for i,j in zip(a1,a2):
print i.ljust(12),':',j
print '-'*8
for i,j in zip(a1,a2):
print i,len(i)
print j,len(j)
输出:
する : dipsy
します : laa-laa
trazan : banarne
した : po
しました : tinky winky
--------
する 6
dipsy 5
します 9
laa-laa 7
trazan 6
banarne 7
した 6
po 2
しました 12
tinky winky 11
谢谢, //弗雷德里克
thanks, //Fredrik
推荐答案
使用unicodedata.east_asian_width
函数,在计算字符串的长度时跟踪哪些字符是窄字符还是宽字符.
Using the unicodedata.east_asian_width
function, keep track of which characters are narrow and wide when computing the length of the string.
#!/usr/bin/python
# coding=utf-8
import sys
import codecs
import unicodedata
out = codecs.getwriter('utf-8')(sys.stdout)
def width(string):
return sum(1+(unicodedata.east_asian_width(c) in "WF")
for c in string)
a1=[u'する', u'します', u'trazan', u'した', u'しました']
a2=[u'dipsy', u'laa-laa', u'banarne', u'po', u'tinky winky']
for i,j in zip(a1,a2):
out.write('%s %s: %s\n' % (i, ' '*(12-width(i)), j))
输出:
する : dipsy
します : laa-laa
trazan : banarne
した : po
しました : tinky winky
某些Web浏览器字体看起来不正确,但是在终端窗口中它们正确对齐.
It doesn’t look right in some web browser fonts, but in a terminal window they line up properly.
这篇关于Python UTF-8,如何对齐打印输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文