my_str.expandtabs(number))
number : optional , number of space to replace tab character.
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 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
You can set a custom number of spaces to replace each tab:
text = 'a\tb\tc'
print(text.expandtabs(4)) # Output: 'a b c'
Convert tabs into spaces for consistent code indentation:
code_snippet = 'def func():\n\tprint("Hello")'
print(code_snippet.expandtabs(4))
def func():
print("Hello")
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
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.