Python String expandtabs() Method

The expandtabs() method returns a string with all tab characters \t replaced with one or more space, depending on the number of characters before \t and the specified tab size.

Syntax:

str.expandtabs(tabsize)

Parameters:

tabsize: size of whitespaces characters to replace \t. Default is 8.

Return Value:

Returns a string where all '\t' characters are replaced with whitespace characters until the next multiple of tab size parameter.

The following example demonstrates the expandtabs() method with default tab size 8.

Example:
>>> '1234\t'.expandtabs()
'1234    '
>>> '1234\t1234'.expandtabs()
'1234    1234'
>>> '1234\t1234\t'.expandtabs()
'1234    1234    '

In the above example, the expandtabs() method on the string '1234\t' replaces the \t with 4 spaces, because the default tab size is 8, consider it as column size, a string '1234\t' already contains 4 characters '1234' except \t. So, the expandtabs() method replaces 4 spaces with \t and makes it 8 chars column.

In the same way, for a string '1234\t1234', \t is an end of the first column with default size 8. So the resulted string would be '1234    1234'. For a string '1234\t1234\t', it makes two columns by adding 4 spaces in each column '1234 1234 '.

Thus, the expandtabs() method creates columns based on the specified tab size.

Specify Tab Size

You can specify a different tab size than the default size 8.

Example:
>>> '12\t'.expandtabs(4)
'12  '
>>> '12\t12'.expandtabs(4)
'12  12'
>>> '12\t12\t'.expandtabs(4)
'12  12  '

If the length of the words is equal to the tab size then expandtabs() will add the number whitespaces after each word will be equal to tab size argument passed.

Example:
>>> '1234\t'.expandtabs(4)
'1234    '
>>> '1234\t1234'.expandtabs(4)
'1234    1234'
>>> '1234\t1234\t'.expandtabs(4)
'1234    1234    '

In the above example, '1234\t' will be '1234    '. It creates another column after '1234' because it already contains four characters, which is equal to the specified tab size.

Now, consider the following example where the length of each word is greater than the tab size.

Example:
>>> '1234\t12345\t'.expandtabs(3)
'1234  12345 '

In the above example, the length of each word in a string '1234\t12345\t' is more than the specified tab size 3. So, the expandtabs() method creates a column of 3 chars and restart counting after 3 chars. It replaces '1234\t' with '1234  ' where \t replaced with two spaces because the second column starts from '4' and so the first column would be '123' and the second column would be '4  ' thus it would be '1234  '. Then, the second part, '12345\t' will result in '12345 ' because '123' is one column and '45 ' is second column. Thus, '1234\t12345\t'.expandtabs(3) will result in '1234  12345 '.