运行环境:python3.x + ubuntu
def print_table(table):
max_width = 0 # 取table中最长元素
for x in table:
if len(x) > col_width:
max_width = len(x)
max_width = max_width * 2
for x in table:
print('{:{}}'.format(x, max_width) + '|')
英文可以正常对齐:
>>> en = ['hello', 'world', 'hi', 'bug']
>>> print_table(en)
hello |
world |
hi |
bug |
中文无法无法正常对齐:
>>> ch = ['上海', '北京', '黑龙江', '乌鲁木齐']
>>> print_table(ch)
上海 |
北京 |
黑龙江 |
乌鲁木齐 |
请问这是什么原因?我观察了一下好像是中文字符在终端下面的输出都是占用了两个空格,但是英文只占用了一个空格。如果是这样,有什么好的解决方法?
Change the font of the terminal to a fixed-width font, such as the more eye-catching Consolas, Adobe's open source font Source Code Pro...
The length of Unicode strings is calculated based on the number of characters rather than the "displayed width". A Chinese character and a Western character are both counted as 1, so they are not aligned. You can use the additional wcwidth package to calculate the number of cells occupied by a character.
The solution is to use Chinese full-width space padding, which should help you.
segmentfault.com/q/1010000008288733/a-1020000008291692