How to Use expandtabs in Python: Syntax and Examples
In Python,
expandtabs() is a string method that replaces tab characters (\t) with spaces. You can specify the number of spaces per tab by passing an integer to expandtabs(tabsize), where tabsize defaults to 8 if not provided.Syntax
The expandtabs() method is called on a string and returns a new string where all tab characters (\t) are replaced by spaces.
tabsize(optional): Number of spaces to replace each tab. Default is 8.
python
string.expandtabs(tabsize=8)Example
This example shows how expandtabs() replaces tabs with spaces. You can change the number of spaces per tab by setting tabsize.
python
text = "Hello\tWorld!\tPython" print("Original string:") print(text) print("\nAfter expandtabs() with default tabsize:") print(text.expandtabs()) print("\nAfter expandtabs() with tabsize=4:") print(text.expandtabs(4))
Output
Original string:
Hello World! Python
After expandtabs() with default tabsize:
Hello World! Python
After expandtabs() with tabsize=4:
Hello World! Python
Common Pitfalls
One common mistake is forgetting that expandtabs() does not change the original string but returns a new one. Also, not specifying tabsize means tabs expand to 8 spaces, which might not fit your layout.
Another pitfall is assuming it works on strings without tabs; it will return the string unchanged.
python
text = "A\tB" text.expandtabs(4) # This returns a new string but does not change 'text' print(text) # Still contains tabs # Correct way: new_text = text.expandtabs(4) print(new_text)
Output
A B
A B
Quick Reference
| Method | Description | Default tabsize |
|---|---|---|
| expandtabs(tabsize=8) | Replaces tabs with spaces in a string | 8 |
| expandtabs(4) | Replaces tabs with 4 spaces | 4 |
| expandtabs(0) | Removes tabs by replacing with zero spaces | 0 |
Key Takeaways
Use
expandtabs() to replace tabs with spaces in strings.The
tabsize parameter controls how many spaces replace each tab.expandtabs() returns a new string; it does not modify the original.Default
tabsize is 8 spaces if not specified.If the string has no tabs,
expandtabs() returns it unchanged.