Skip to content
Python expandtabs: align to tab stops instead of inserting fixed spaces

Python expandtabs: align to tab stops instead of inserting fixed spaces

November 20, 2026

A tab advances to the next tab stop. Replacing every tab with four spaces will not produce the same result as expanding tabs at four-column intervals.

Set up

Tested on Linux with CPython 3.12.14. Use Python 3.12 or later, Bash, a text editor, mktemp, rm and rmdir. The example needs no network access. Run the steps in the same terminal and stop if setup fails. Run Python without -O so the assertions stay enabled.

start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1

Run the example

Save this as tab_stops.py:

samples = ["a\tX", "abcd\tX", "ab\tX", "a\tX\nab\tY"]
for text in samples:
    print(repr(text), "=>", repr(text.expandtabs(4)))
print("fixed spaces:", repr("ab\tX".replace("\t", "    ")))
print("zero tabsize:", repr("ab\tX".expandtabs(0)))
assert "a\tX".expandtabs(4) == "a   X"
assert "abcd\tX".expandtabs(4) == "abcd    X"

Run:

python3 -B tab_stops.py

Observed output:

'a\tX' => 'a   X'
'abcd\tX' => 'abcd    X'
'ab\tX' => 'ab  X'
'a\tX\nab\tY' => 'a   X\nab  Y'
fixed spaces: 'ab    X'
zero tabsize: 'abX'

Count from the start of each line

The expandtabs documentation defines tab stops at multiples of tabsize. At column one, a four-column tab stop needs three spaces. At column four, the next stop is column eight, so the tab needs four spaces. Carriage return and newline reset the column count.

The repr output makes inserted spaces and the line break visible. A zero tab size removes tabs. Pick an explicit positive tab size when aligning ordinary text, rather than relying on different editors to share the default.

Limits

Python counts each other character as one column for this operation. That is not a terminal display-width calculation: wide Unicode characters, combining marks and escape sequences can occupy a different visible width. Use a display-aware formatter for those cases. Expanding tabs is also lossy; the resulting spaces do not record which spaces originally came from tabs.

Clean up

Remove the example file and the temporary directory:

rm -- tab_stops.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dir

Acknowledgements

This post was created with assistance from AI.

Last updated on