Python String expandtabs() Method

Expands tabs in a string by replacing the tab with the number of spaces specified by tab size. The function defaults to 8 spaces per tab when tab size isn't provided. This method converts all the tab characters(\t) with whitespace.

The number of whitespaces used depends upon the value of the argument tab size. The number of whitespaces to be used is the difference between the current position and the next stopping position(a multiple of tab size).

Syntax:

string.endswith(tabsize)

This endswith() method accepts a single parameters.

tabsize The method takes a single argument that is tabsize.(Default tabsize=8).
Return Value:

This method returns a string with all the tab characters replaced with whitespaces.

			

# Python example of the expandtabs() method.

exampleString1 = "If a\t person is\t riding like\t lightning, then that person will crash like\t thunder."
 
print(exampleString1.expandtabs())        //1
 
print(exampleString1.expandtabs(4))    //2
 
print(exampleString1.expandtabs(7))    //3

print(result)


				

Output:

If a person is riding like lightning, then that person will crash like thunder. If a person is riding like lightning, then that person will crash like thunder. If a person is riding like lightning, then that person will crash like thunder.

Here, we can see that in the output of the expandtabs() method, in the first case, the tab size by default is 8. So, the first tab occurs at position 3(assuming we start with index=0). And the next stopping position is 7(since (tabsize*1)-1=7).

So the number of whitespaces used will be 7-3=4 whitespaces. Similarly, the next stopping positions will be 15,23,31, and so on.

Now, the next tab character occurs at position 16, and the next stopping position is 23. The number of white spaces used will be 23-16=17 whitespaces.

Another example of replacing tabs with whitespace.

			

# Python example of the expandtabs() method.

str = "Nothing is\timpossible!!!"
print (str)
print (str.expandtabs())
print (str.expandtabs(16))

				

Output:

Nothing is impossible!!! Nothing is impossible!!! Nothing is impossible!!!