在Python中,输出中文时对齐问题可以通过以下几种方法解决:
1. 使用Texttable库:
from texttable import Texttable
table = Texttable()
table.set_cols_dtype(['t', 't'])
table.set_cols_align(['l', 'r'])
table.set_cols_width([100, 50])
rows = [
['用户词典', '12356', 'Univ Cordoba, Cordoba, Spain.'],
['物品用户词典', '25', '254']
]
table.add_rows(rows)
print(table.draw())
def get_len(string: str) -> int:
length = 0
for ch in string:
if '\u4e00' <= ch <= '\u9fff': 判断是否为中文字符
length += 2
else:
length += 1
return length
示例
s1 = '用户词典'
d1 = '12356'
s2 = '物品用户词典'
d2 = '25'
s3 = 'Univ Cordoba, Cordoba, Spain.'
d3 = '254'
计算每列长度
len1 = get_len(s1)
len2 = get_len(d1)
len_mid = max(len1, len2) + 2 加上2个字符宽度作为间隔
输出
print(f'{s1:<{len1}} {d1:<{len2}} {s3:<{len_mid}}')
3. 使用str.format进行格式化输出,并考虑中文字符宽度:
使用中文空格进行对齐
print('{:<10} {:<20} {:<10}'.format('清华大学', '中国科学技术大学', '复旦大学'))
4. 使用Textwrap库进行文本对齐:
import textwrap
data = [
('清华大学', '10'),
('中国科学技术大学', '10'),
('复旦大学', '10')
]
计算每列最大宽度
col_widths = [max(len(item) for item in col) for col in zip(*data)]
输出
for row in data:
print(textwrap.fill(' '.join(str(item).ljust(width) for item, width in zip(row, col_widths)),
initial_indent=' ', subsequent_indent=' '))
以上方法可以帮助你在Python中实现中文输出对齐。请根据你的具体需求选择合适的方法