expandtabs()

my_str.expandtabs(number))
number : optional , number of space to replace tab character.

By default expandtabs() ads 8 space by replacing all tab characters. We can set the number of spaces by giving input parameter.
my_str='a\tbc\tdef\tghij\tklmno'
my_str=my_str.expandtabs()
print(my_str)
Output
a       bc      def     ghij    klmno
my_str='a\tbc\tdef\tghij\tklmno'
my_str=my_str.expandtabs(1)
print(my_str)
Output
a bc def ghij klmno

Use Case: Formatting Text for Output

Use expandtabs() to format text with consistent spacing in reports or tables:

text = 'Name\tAge\tOccupation\nAlice\t30\tEngineer'
formatted_text = text.expandtabs(12)
print(formatted_text)
Output
Name        Age         Occupation
Alice       30          Engineer

Using a Custom Tab Width

You can set a custom number of spaces to replace each tab:

text = 'a\tb\tc'
print(text.expandtabs(4))  # Output: 'a   b   c'

Use Case: Converting Code Indentation

Convert tabs into spaces for consistent code indentation:

code_snippet = 'def func():\n\tprint("Hello")'
print(code_snippet.expandtabs(4))

def func():
    print("Hello")

Aligning Multiple Columns

Use expandtabs() to align columns of data properly:


data = 'Item\tPrice\tQuantity\nApple\t1.5\t10\nBanana\t0.5\t20'
print(data.expandtabs(10))
Item      Price     Quantity
Apple     1.5       10
Banana    0.5       20

All String methods


Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer