Tutorial Study Image

Python expandtabs()

The expandtabs() function in python helps to replace the '\t' character with white space inside the string. The function allows specifying the amount of space required. Finally, the modified string is returned as output.

string.expandtabs(tabsize) #where tabsize is an integer value 

expandtabs() Parameters:

The expandtabs() function takes a single parameter.If we need to replace multiple tab characters, then the characters before the tab are counted only when it reaches the previous tab character.

Parameter Description Required / Optional
tabsize A number specifying the tabsize. Default tabsize is 8 Optional

expandtabs() Return Value

The return value is always a string. It returns the copy of the original string after expansion using white space.

Input Return Value
string string with whitespaces

Examples of expandtabs() method in Python

Example 1: How to use expandtabs() without argument?


string = 'abc\t56789\tefg'

# no argument is passed
# default tabsize is 8
result = string.expandtabs()

print(result)
 

Output:


abc     56789   efg

Example 2: How expandtabs() with different argument?


string = "abc\t56789\tdef"
print('Original String:', str)

# tabsize is set to 2
print('Expanded tabsize 2:', string.expandtabs(2))

# tabsize is set to 3
print('Expanded tabsize 3:', string.expandtabs(3))

# tabsize is set to 4
print('Expanded tabsize 4:', string.expandtabs(4))

# tabsize is set to 5
print('Expanded tabsize 5:', string.expandtabs(5))

# tabsize is set to 6
print('Expanded tabsize 6:', string.expandtabs(6))
 

Output:


Original String: abc 56789 def
Expanded tabsize 2: abc 56789 def
Expanded tabsize 3: abc   56789 def
Expanded tabsize 4: abc 56789   def
Expanded tabsize 5: abc  56789     def
Expanded tabsize 6: abc   56789 def