expandtabs(): set the number of spaces for a tab in a string in Python

Use the expandtabs() method to set the number of spaces for a tab.

You can set any number of spaces, but when no argument is given, the default is 8.

Basic Usage

my_string = 'B\tR'

print(my_string.expandtabs())
#output: B       R

Notice the 7 spaces between the letters B and R.

The \t is at position two after one character, so it will be replaced with 7 spaces.

Let’s look at another example.

my_string = 'WORL\tD'

print(my_string.expandtabs())
#output: WORL    D

Since WORL has four characters, the \t is replaced with 4 spaces to make it a total of 8, the default tabsize.

The code below gives us 4 spaces for the first tab after four characters ‘WORL’ and 7 spaces for the second tab after one character ‘D’.

my_string = 'WORL\tD\tCUP'

print(my_string.expandtabs())
#output: WORL    D       CUP

Custom Tabsize

It is possible to set the tabsize as needed.

In this example the tabsize is 4, which gives us 3 spaces after the char ‘B’.

my_string = 'B\tR'

print(my_string.expandtabs(4))
#output: B   R

This code has tabsize set to 6, which gives us 5 spaces after the char ‘B’.

my_string = 'B\tR'

print(my_string.expandtabs(6))
#output: B     R