Last Updated : 11 Jul, 2025
expandtabs() method in Python is used to replace all tab characters (\t) in a string with spaces. This method allows for customizable spacing, as we can specify the number of spaces for each tab. It is especially useful when formatting text for better readability or alignment. Let's understand with the help of an example:
Python
s = "Name\tAge\tLocation"
# Expanding tabs with the default spacing
res = s.expandtabs()
print(res)
Explanation:
string.expandtabs(tabsize)
Parameters: tabsize (optional) : Specifies the number of spaces per tab. The default value is 8.
Return Type: This method returns a new string with all the tab characters replaced with spaces.
Examples of expandtabs() method 1. Using default tab sizeWhen we call the expandtabs() method without any arguments, it uses the default tab size of 8 spaces. This default behavior ensures that basic alignment is achieved without additional configuration.
Python
s = "A\tB\tC"
# Expanding tabs with default tab size
res = s.expandtabs()
print(res)
Explanation:
We can specify a custom tab size using the tabsize parameter. This allows us to format strings based on specific alignment requirements.
Python
s = "Python\tis\tfun"
# Expanding tabs with a custom size of 4 spaces
res = s.expandtabs(4)
print(res)
Explanation:
When working with text that contains both tabs (\t) and regular characters, Python’s expandtabs() method ensures proper alignment by replacing tabs with the appropriate number of spaces based on the specified tab size.
Python
s = "A\tBC\tDEFG"
# Expanding tabs with a size of 5 spaces
res = s.expandtabs(5)
print(res)
Explanation:
If the string does not contain any tabs, the method returns the original string unchanged. This ensures efficiency and avoids unnecessary processing.
Python
s = "Python is fun!"
# Expanding tabs in a string without tabs
result = s.expandtabs(4)
print(result)
Explanation: Since there are no tabs in the input string, the expandtabs() method has no effect.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4