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

1586010002-jmsa.png

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)

Output:

する : 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

解决方案

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))

Outputs:

する : dipsy

します : laa-laa

trazan : banarne

した : po

しました : tinky winky

It doesn’t look right in some web browser fonts, but in a terminal window they line up properly.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值