Python可以很容易地填充和对齐ascii字符串,如下所示:
>>> print "%20s and stuff" % ("test")
test and stuff
>>> print "{:>20} and stuff".format("test")
test and stuff
Run Code Online (Sandbox Code Playgroud)
但是,如何正确填充和对齐包含特殊字符的unicode字符串?我尝试了几种方法,但它们似乎都没有用:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def manual(data):
for s in data:
size = len(s)
print ' ' * (20 - size) + s + " stuff"
def with_format(data):
for s in data:
print " {:>20} stuff".format(s)
def with_oldstyle(data):
for s in data:
print "%20s stuff" % (s)
if __name__ == "__main__":
data = ("xTest1x", "?Test?", "?? Test ??", …Run Code Online (Sandbox Code Playgroud) 我有一个包含日语字符和"正常"的数组.如何对齐这些打印输出?
#!/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)
Run Code Online (Sandbox Code Playgroud)
输出:
?? : 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
Run Code Online (Sandbox Code Playgroud)
谢谢,// Fredrik
from prettytable import PrettyTable
header="????,??,????".split(",")
x = PrettyTable(header)
x.align["????"]="l"
table='''HuangTianhui,?,1948/05/28
???,?,1952/03/27
???,?,1994/12/09
LuiChing,?,1969/08/02
???,?,1982/03/01
???,?,1983/08/03
YangJiabao,?,1988/08/25
????·???,?,1979/07/10
???,?,1949/10/20
???(??),?,2011/02/25
(??????),?,1985/07/20
'''
data=[row for row in table.split("\n") if row]
for row in data:
x.add_row(row.strip().split(","))
print(x)
Run Code Online (Sandbox Code Playgroud)

我想要的输出格式如下.

在这个例子中,prettytable.py无法显示字符的正确中国暧昧宽度 ·在 ????·??? ,则字符含糊的宽度.如何修复prettytable.py中的错误?
我在prettytable.py的def _char_block_width(char)中添加了两行,但问题仍然存在.
if char == 0xb7:
return 2
Run Code Online (Sandbox Code Playgroud)
我已经解决了,文件prettytable.py应该安装在我的电脑d:\ python33\Lib\site-packages中directly not in as the form of d:\python33\Lib\site-packages\prettytable\prettytable.py
有很多中文字符宽度不明确,我们添加两行如下来修复bug是愚蠢的,如果有50个不明确的字符,在prettytable.py中会添加100行,有没有简单的方法要做到这一点?只修一些线来对待所有模棱两可的角色?
if char == 0xb7:
return 2
Run Code Online (Sandbox Code Playgroud) 我正试图将UTF-8编码的字符串对齐string.ljust.提出这个例外:UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128).例如,
s = u"??" // a Chinese string
stdout.write(s.encode("UTF-8").ljust(20))
Run Code Online (Sandbox Code Playgroud)
我是在正确的轨道上吗?或者我应该使用其他方法进行格式化?
谢谢和最诚挚的问候.