Python string expandtabs() function returns a new string with tab characters (t) replaced with one or more whitespaces.
Python String expandtabs()
This function syntax is:
str.expandtabs(tabsize=8)
We can specify the tabsize parameter to specify the number of whitespaces to use when expanding the tab characters. The default value of the tabsize parameter is 8.
Python takes into account the characters present before the tab character is found. The number of whitespaces to use is equal to the tabsize minus the number of characters before the tab character.
If the number of characters is more than the tabsize then the next multiple of tabsize is used i.e. 8,16,24 and so on.
If there are multiple tab characters to be replaced, then the characters before the tab are counted only until the previous tab character is reached.
Python String expandtabs() example
Let’s look at a simple example of expandtabs() function.
s="AtBtCtD"
print(s.expandtabs())
# Output:
# A B C D
Notice that there is exactly one character before every tab character, so 7 whitespaces are used to replace tab character.
Let’s look at another example with more characters before tab character.
s="ABCDtEtF"
print(s.expandtabs())
# Output:
# ABCD E F
There are 4 characters before the first tab character, so 8-4=4 whitespaces are used to expand the tab character.
For the second tab character, there is only 1 character before it, so 8-1=7 whitespaces are used to expand the tab character.
Let’s look at another example where the number of characters before tab character is more than the tabsize.
s="ABCDEFGHIJKtG"
print(s.expandtabs())
# Output:
# ABCDEFGHIJK G
There are 11 characters before the tab, so 8*2-11=5 whitespaces are used to expand the tab.
Let’s look at another example of this scenario.
s="ABCDEFGHIJKttG"
print(s.expandtabs())
# Output:
# ABCDEFGHIJK G
The first tab is expanded with 8*2-11=5 whitespaces whereas the second tab is expanded with 8-0=8 whitespaces. That’s why there are 13 whitespaces in the output string.
Python string expandtabs() with tabsize
Let’s look at some examples with variable tabsize.
s="ABCtD"
print(s)
print(s.expandtabs())
print(s.expandtabs(tabsize=0))
print(s.expandtabs(tabsize=1))
print(s.expandtabs(tabsize=2))
print(s.expandtabs(tabsize=3))
print(s.expandtabs(tabsize=4))
print(s.expandtabs(tabsize=5))
print(s.expandtabs(tabsize=6))
print(s.expandtabs(tabsize=7))
Just follow the rules above and you will be able to easily understand the output.
Can we specify a negative value for tabsize? Let’s check it out with a simple code snippet.
s="ABCtD"
print(s.expandtabs(tabsize=-1))
print(s.expandtabs(tabsize=-3))
Output:
ABCD
ABCD
It’s clear that Python is using tabsize as 0 when a negative tabsize value is provided and doesn’t throw any error.
Reference: Official Documentation