您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python UTF-8,如何对齐打印输出

Python UTF-8,如何对齐打印输出

使用该unicodedata.east_asian_width函数,在计算字符串的长度时,跟踪哪些字符窄和宽。

#!/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浏览器字体中,它看起来不正确,但是在终端窗口中,它们正确对齐。

python 2022/1/1 18:34:46 有247人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶