bytes.expandtabs()
Not "tab becomes N spaces". Each tab advances to the next tab STOP, so the number of spaces depends on where the tab sits — which is what makes columns line up.
Demo
Compare the first two cases. After one character, a tab with tabsize 4 becomes three spaces, landing on column 4. After three characters the same tab becomes ONE space, because column 4 is only one step away. That is the tab-stop rule: the tab fills up to the next multiple of tabsize, however far that is. With tabsize 0 the tabs are simply deleted.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| tabsize | int | no (8) | Distance between tab stops in bytes. A tabsize of 0 removes tabs entirely. |
Return value
bytes — A new bytes object with each tab replaced by enough spaces to reach the next multiple of tabsize. The column resets at each newline.
Common patterns
clean = line.expandtabs(4)
record = raw.expandtabs(8)
no_tabs = data.expandtabs(0)
Examples
Pitfalls
b'abc\td'.replace(b'\t', b' ')
b'abc\td'.expandtabs(4)
'é\tb'.encode().expandtabs(4)
'é\tb'.expandtabs(4).encode()
data.expandtabs(4) data
data = data.expandtabs(4)
When to use
- Aligning tabbed input for display or a fixed-width parser
- Normalising whitespace before comparing lines
- Removing tabs with tabsize 0
- You want a fixed number of spaces per tab → replace
- Text with non-ASCII characters → decode first
- The data is binary — tab bytes may be meaningful
Notes
FAQ
Because the tab only needs to advance to the NEXT tab stop. If the data is already at column 3 and stops are every 4, one space reaches column 4. That is what keeps the following text aligned across lines with different prefixes.
b'a\tb'.expandtabs(4) # b'a b' b'abc\tb'.expandtabs(4) # b'abc b'