Python expandtabs() Method

Definition
In Python, expandtabs() returns a new string where each tab (\t) becomes spaces up to the next tab stop.
tabsize is optional and defaults to 8. The number of spaces depends on column position, not a fixed count.
Syntax
Call expandtabs on the string. Start with this line.
aligned = text.expandtabs(4)
| Call | What it does |
|---|
"a\tb".expandtabs(8) | Expands the tab to the next stop. |
"a\tb".expandtabs(4) | Uses tab stops every 4 columns. |
Newlines reset the column counter for the next line.
Library declarations
str.expandtabs(tabsize=8) → str
Parameters
| Parameter | Description |
|---|
| tabsize | Optional. Spaces between tab stops. Default 8. |
Return Value
| Return Value | Description |
|---|
| str | A new string with tabs expanded to spaces. |
Python Examples
Example 1 — Default Tab Size
Expand tabs with the default stop width of 8 and prove the original string stays unchanged.
original = "Name\tAge\tCity"
result = original.expandtabs()
print(repr(original))
print(repr(result))
'Name\tAge\tCity'
'Name Age City'
How It Works
- Store tabs.
original still holds real \t characters. - Default size.
expandtabs() uses tabsize=8. - Align columns. Each tab adds enough spaces to reach the next stop of 8.
- Original untouched. Immutability keeps the tab characters in
original.
Example 2 — Custom tabsize
Smaller stops pack columns tighter. Notice how space count depends on current column length.
print(repr("A\tB".expandtabs(4)))
print(repr("ABCD\tE".expandtabs(4)))
How It Works
- Short prefix.
"A" ends at column 1 → tab needs 3 spaces to reach 4. - Longer prefix.
"ABCD" ends at column 4 → already on a stop, so tab adds 4 spaces to reach 8. - Same tabsize. Both calls use
4, but space counts differ. - Column math. Spaces =
tabsize - (column % tabsize).
Example 3 — expandtabs() vs replace()
Fixed replacement cannot align columns the way tab stops do.
row = "A\tB"
print("expandtabs:", repr(row.expandtabs(4)))
print("replace: ", repr(row.replace("\t", " ")))
expandtabs: 'A B'
replace: 'A B'
How It Works
- Same input. Both start from
"A\tB". - expandtabs(4). Inserts 3 spaces to hit column 4 →
"A B". - replace. Always inserts exactly 4 spaces →
"A B". - Pick by goal. Column alignment →
expandtabs; fixed swap → replace.
Frequently Asked Questions
It replaces tabs with spaces aligned to tab stops.
string.expandtabs(tabsize=8). tabsize is optional.
No. It returns a new string.
replace() uses a fixed space count. expandtabs() aligns to columns.
When displaying or cleaning tab-separated text before printing.
Next: find()
Learn how to search for a substring and get its index.
find() →About the author
Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
9 people found this page helpful