bytes.expandtabs() returns a new bytes object where every tab byte (\t, value 9) is replaced by one or more spaces so that the text after it starts at the next tab stop. Tab stops are every tabsize columns, 8 by default.
The column counter starts at zero and goes back to zero after each \n or \r byte. Every other byte, including non-ASCII ones, counts as one column, which is only correct for single-byte text.
bytes.expandtabs() is a method of the built-in bytes type: call it on a bytes object with dot notation, such as data.expandtabs(...). No import is needed, and bytearray objects have the same method.
Syntax
Optionally pass the distance between tab stops.
python
result = data.expandtabs()
result = data.expandtabs(tabsize)
Call
What it does
b"a\tb".expandtabs()
Returns b'a b': 7 spaces to column 8.
b"a\tb".expandtabs(4)
Returns b'a b'.
b"a\tb".expandtabs(0)
Returns b'ab': tabs are removed.
A tab right at a tab stop still produces a full tabsize run of spaces.
Method signatures
python
bytes.expandtabs(tabsize=8)
# returns a new bytes object (bytearray.expandtabs() returns a bytearray)
Parameters
Parameter
Description
tabsize
Optional. Number of columns between tab stops. Default 8. Zero or a negative value removes the tabs.
Return Value
Return Value
Description
bytes
A copy with tabs replaced by spaces.
Python Examples
Example 1 — See Exactly How Many Spaces Are Inserted
Replace spaces with dots after expanding so the padding becomes visible, first with the default stops and then with a tab size of 4.