Expandtabs Turns Tabs Into Aligned Columns

expandtabs walks each tab to the next tab stop so tab-separated rows line up in a terminal; a tab size wider than the longest cell keeps columns aligned.

PythonCli Tooling

Code

pythonsnippet
19 lines
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)))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

What the demo aligns

Each row embeds tab separators between id, name and region. expandtabs with no argument walks every tab to the next multiple-of-8 stop, so the first printed block shows the default alignment: id at column 0 and name pushed to 8.

The custom size shifts the stops: expandtabs(10) aligns columns at multiples of 10, wide enough for the longest cell cleopatra. The length comparison closes it; the raw length counts the single tab characters while the expanded string measures the real rendered width.

Caveats and details

  • Column width depends on the field before the tab, not the tab itself.
  • Tab stops restart after each non-tab character.

Interactive Tools for This Topic

FAQ

How wide should the tab size be?
At least one wider than the longest cell in the column; the demo uses 10 so every name, including cleopatra, lands flush at the next stop.