实现要点
每行在 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)))