str.expandtabs()
Tabs become variable spaces — align to the next tab stop, not add a fixed count.
Demo
Each tab expands to enough spaces to reach the next TAB STOP — a multiple of tabsize. That means the number of spaces inserted DEPENDS on the current column. In "ab\tc" with tabsize=4, the tab inserts 2 spaces (columns 2,3) to reach column 4. In "a\tc" with tabsize=4, the tab inserts 3 spaces. Newlines (\n) and carriage returns (\r) RESET the column counter to 0. tabsize=0 removes tabs entirely.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| tabsize | int | no (8) | The tab stop width in columns. Every tab expands to enough spaces to reach the next multiple of tabsize. tabsize=0 removes tabs entirely. |
Return value
str — A copy of the string where every tab (U+0009) is replaced with spaces to align the following character at the next multiple of tabsize columns. Newlines and carriage returns reset the column counter to 0.
Common patterns
code_with_spaces = code_with_tabs.expandtabs(4)
for name, age in people: print(f"{name}\t{age}".expandtabs(16))
for line in text.expandtabs(4).splitlines(): ...
no_tabs = text.expandtabs(0)
Examples
Pitfalls
"ab\tcd".replace("\t", " ")
"ab\tcd".expandtabs(4)
# expected tabs to continue counting from before \n"aaaa\tb\nc\td".expandtabs(4)
"a\tb".expandtabs(0)
# tabsize=0 is documented as tab-removal"漢\tb".expandtabs(4)
import wcwidth # manual alignment based on wcwidth.wcswidth()
When to use
- Converting tab-indented code to spaces (a common pre-commit step)
- Aligning columns of a data table for display
- Normalizing text before layout or width calculations
- Preparing content for a rendering context that does not support tabs
- "Insert N spaces where a tab was" → str.replace is simpler
- Visual-width alignment with wide characters → use wcwidth
- Tab-to-tab spacing (not fill) → do it manually
- Regex-based tab handling → probably overkill
Notes
FAQ
replace inserts a FIXED number of characters everywhere a tab appears. expandtabs inserts a VARIABLE count that aligns the next character to the next tab stop. Only expandtabs preserves the "tab stop" alignment property.