Python Reference ยท String Methods
Python str.expandtabs() method
Reference for Python str.expandtabs(): replace tab characters with spaces up to the next tab stop, set the tab size and see how columns line up.
The str.expandtabs() method returns a copy of a string in which every tab character ("\t") is replaced by enough spaces to reach the next tab stop. Tab stops are placed every 8 columns by default, and you can choose another size.
A tab is not a fixed number of spaces: its width depends on the column it starts in. That is why this method tracks the current column, which restarts after each newline or carriage return.
print("a\tb".expandtabs(4).replace(" ", ".")) # a...b
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
str.expandtabs(tabsize=8)
| Name | Description |
|---|---|
tabsize |
Optional. The distance between tab stops, as an int. Default 8. A value of 0 or less removes tabs. |
Return value: a new str.
Raises: TypeError if tabsize is not an integer.
Usage notes
- Column aware. The tab fills only up to the next multiple of
tabsize, so one tab may become 1 totabsizespaces. - Newlines reset the column. After
"\n"or"\r"the count starts at zero, which is why multi-line text still lines up. - Other characters count as one column. Escape sequences and wide characters are not measured by display width.
- Only
\tis replaced. Other whitespace such as vertical tabs stays unchanged. - Original is unchanged. Strings are immutable; assign the result.
- Alignment tools. For generated tables,
ljust()or format specs such asf"{name:<12}"are more predictable than tabs. - Source code. Mixing tabs and spaces for indentation is an error in Python 3 (
TabError), so converting files withexpandtabs()is a common cleanup step.
Related
str.ljust(),str.rjust(),str.center(),str.replace(),str.split()- Lessons: Strings, String methods