← 中文资源

简体中文版本

expandtabs 对齐制表符列

expandtabs 把每个 跳到下一个制表位,制表符分隔的行在终端里对齐;制表位要比最宽的单元格更宽,展开后的长度才是真实列宽。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

default tabsize:
id      name    region
1       alice   us-east-1
2042    bob     ap-south-2
37      cleopatra       eu-west-3
custom tabsize=10:
id        name      region
1         alice     us-east-1
2042      bob       ap-south-2
37        cleopatra eu-west-3
raw length: 22 expanded: 29

实现要点

每行在 id、name、region 之间嵌制表符。expandtabs 不带参数时把每个 tab 跳到 8 的倍数制表位,第一块输出展示默认对齐——id 在第 0 列,name 推到第 8 列。

自定义尺寸移动制表位:expandtabs(10) 按 10 的倍数对齐,宽到容得下最长的 cleopatra。长度比较收尾——原始长度数的是单个 tab 字符,展开后的字符串度量真实渲染宽度。

细节提醒

  • 列宽取决于 tab 之前的字段,而不是 tab 本身。
  • 制表位在每个非 tab 字符后重新起算。

核心语句

print(row.expandtabs(10))

代码示例

rows = [
    "id\tname\tregion",
    "1\talice\tus-east-1",
    "2042\tbob\tap-south-2",
    "37\tcleopatra\teu-west-3",
]

# Tab stops default to 8: every \t jumps to the next multiple of 8
print("default tabsize:")
for row in rows:
    print(row.expandtabs())

# Pick a tab size wider than the longest cell and every column lines up
print("\ncustom tabsize=10:")
for row in rows:
    print(row.expandtabs(10))

# len() counts the raw tab character; the expanded string has the real width
print("\nraw length:", len(rows[3]), "expanded:", len(rows[3].expandtabs(10)))