Python String expandtabs()
Method
The expandtabs() method in Python is used with string objects. It replaces all tab characters (\t
) in a string with spaces. You can also set the number of spaces a tab should expand to.
Syntax
string.expandtabs(tabsize=8)
Parameters:
tabsize
– (Optional) The number of spaces to replace each\t
with. Default is 8.
Returns:
- A new string where all
\t
tab characters are replaced with spaces.
Example 1: Default Tab Size
text = "Python\tRocks!"
print(text.expandtabs())
Python Rocks!
Example 2: Custom Tab Size (tabsize=4)
text = "A\tB\tC"
print(text.expandtabs(4))
A B C
Example 3: With Multiple Tabs and Alignment
data = "Name\tAge\tCity"
print(data.expandtabs(10))
Name Age City
Why Use expandtabs()
?
- To make tabbed text align nicely using spaces
- Useful in formatting outputs, reports, or logs
- Helps standardize formatting across systems (tabs can display differently in different editors)
Common Mistakes
- Forgetting that
expandtabs()
doesn’t modify the original string (strings are immutable) - Using it without understanding how tab size works with alignment (it aligns to the next multiple of tab size)
Interview Tip
This method might come up in string formatting problems where you need to normalize or align data.
Summary
expandtabs()
replaces\t
with spaces- Default tab size is
8
, but you can customize it - Returns a new string (does not change original)
Practice Challenge
Write a Python program that takes a tab-separated string from user input and prints the expanded version using 6 spaces per tab.
user_input = input("Enter a tab-separated string: ")
print(user_input.expandtabs(6))