You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中实现前后单词列表的等距对齐显示?

问题:Python实现两组单词等距对齐显示

我有两组单词数组,一组是处理前的单词,另一组是处理后的单词:

before = ['screen', 'properly', 'salients', 'spoiled', 'respond']
after = ['screens', 'properly', 'salient', 'spoil', 'responds']

print("Before", "|", "After")
print("\t|\t")

for i in range(5):
  print(before[i], "\t|\t", after[i])

我希望将两组单词按行显示,以“|”分隔,格式如“before | after”。但由于单词长度不同,用制表符分隔的排版效果很混乱:

Before | After
    |   
screen  |    screens
properly    |    properly
salients    |    salient
spoiled     |    spoil
respond     |    responds

请问如何在Python中实现单词间的等距对齐?


解决方案

方法1:利用f-string指定固定宽度

先计算before数组中最长单词的长度,以此作为左列的固定宽度(额外加空格优化排版),就能保证所有左列内容对齐,再搭配分隔符和右列内容即可:

before = ['screen', 'properly', 'salients', 'spoiled', 'respond']
after = ['screens', 'properly', 'salient', 'spoil', 'responds']

# 计算左列最大宽度,加2个空格让排版更宽松
max_left_width = max(len(word) for word in before) + 2

# 打印表头
print(f"{'Before':<{max_left_width}}| {'After'}")
# 打印分隔线(可选,增强可读性)
print(f"{'-'*max_left_width}+{'-'*(max(len(word) for word in after)+2)}")

# 逐行配对打印内容
for b_word, a_word in zip(before, after):
    print(f"{b_word:<{max_left_width}}| {a_word}")

输出效果:

Before   | After
---------+--------
screen   | screens
properly | properly
salients | salient
spoiled  | spoil
respond  | responds

方法2:使用str.format()方法实现对齐

核心思路和方法1一致,只是用format语法处理对齐:

before = ['screen', 'properly', 'salients', 'spoiled', 'respond']
after = ['screens', 'properly', 'salient', 'spoil', 'responds']

max_left_width = max(len(word) for word in before) + 2

# 打印表头和分隔线
print("{:<{}}| {}".format("Before", max_left_width, "After"))
print("{:<{}}| {}".format("-"*max_left_width, max_left_width, "-"*(max(len(word) for word in after)+2)))

# 逐行打印
for b_word, a_word in zip(before, after):
    print("{:<{}}| {}".format(b_word, max_left_width, a_word))

输出效果和方法1完全一致。

方法3:用第三方库tabulate快速生成对齐表格

如果需要更规整的表格样式,可以用第三方库tabulate,它会自动处理列对齐:

首先安装库:

pip install tabulate

然后编写代码:

from tabulate import tabulate

before = ['screen', 'properly', 'salients', 'spoiled', 'respond']
after = ['screens', 'properly', 'salient', 'spoil', 'responds']

# 组合数据并添加表头
table_data = list(zip(before, after))
headers = ["Before", "After"]

# 打印左对齐的表格
print(tabulate(table_data, headers=headers, tablefmt="simple", colalign=("left", "left")))

输出效果:

Before   After
-------- --------
screen   screens
properly properly
salients salient
spoiled  spoil
respond  responds

内容的提问来源于stack exchange,提问作者Tananda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 19:19:57