learn python string expandtabs() with example

The expandtabs() method in Python is a built-in method used for string handling. The expandtabs() method replaces all tab characters (“\t”) in the string using multi-space strings, depending upon the system’s tab configuration. If no argument is passed, all tab characters in the string are replaced with 8 spaces.

Syntax:

string.expandtabs(tabsize)

tabsize: This is an optional parameter. If it’s provided, the method will replace all tab characters in the string with the number of spaces specified. Default tabsize is 8.

How to use the expandtabs() method:

str = "Hello\tWorld!"
print(str.expandtabs(4)) # "Hello  World!"

str = "Hello\tWorld!"
print(str.expandtabs()) # "Hello  World!"

Example 1

Handling multiple tab characters in a string. Each “\t” is replaced with two spaces because we have used expandtabs(2).

str = "Hello\tWorld!\tHave\ta\tNice\tDay!"
print(str.expandtabs(2)) # Output: "Hello World! Have a Nice Day!"

Example 2

You can use expandtabs() to replace the tab characters with a fixed number of spaces to maintain a consistent view of the data across various environments.

data = "Name\tAge\tOccupation\nAlice\t24\tEngineer\nBob\t30\tDoctor"
print("Original data:")
print(data)

print("\nData with expandtabs():")
data = data.expandtabs(10) # we're using 10 spaces for alignment purposes
print(data)

Output:

Original data:
Name  Age Occupation
Alice  24 Engineer
Bob   30 Doctor

Data with expandtabs():
Name   Age    Occupation
Alice   24    Engineer  
Bob    30    Doctor  

Leave a Reply

Your email address will not be published. Required fields are marked *