Python String expandtabs() Method

The expandtabs() method is used to replace tab characters (\t) in a string with spaces. By default, a tab is replaced with 8 spaces, but you can specify a different tab size.

Syntax

string.expandtabs(tabsize)

Parameter

tabsize (Optional): An integer specifying the number of spaces to replace each tab character. Default is 8.

Return Value

Returns a new string with tab characters replaced by spaces.

Examples

Default tabsize

If you don’t specify a tabsize, it defaults to 8.

text = "apple\tbanana\tmango"
expanded_text = text.expandtabs()
print(expanded_text) # Output: "apple   banana  mango"

Custom tabsize

text = "apple\tbanana\tmango"
expanded_text = text.expandtabs(4)
print(expanded_text) # Output: "apple   banana  mango"

How the expandtabs() Method Works

The expandtabs() method doesn’t just blindly replace each tab character with 4 spaces. Instead, it adds enough space to move the cursor to the next tab stop based on the current position.

The expandtabs(4) method sets tab stops every 4 characters (i.e. at positions 4, 8, 12, 16, and so on).

Let’s simulate the character’s position.

Part 1: "apple"

  • "apple" has 5 characters.
  • Current position: 5
  • Next tab stop (Next multiple of 4) = 8
  • So, \t after "apple" is expanded to 8 - 5 = 3 spaces.

Now we have:

"apple   banana\tmango"
        ↑ (cursor at position 8)

Part 2: "banana"

  • "banana" is 6 characters.
  • New position after "banana": 8 + 6 = 14
  • Next tab stop = 16
  • So, \t after "banana" is expanded to 16 - 14 = 2 spaces.

Now, we have:

"apple   banana  mango"
                      ↑ (cursor at position 16)

Final Output:

"apple   banana  mango"

Hence, the tabs are replaced with 3 and 2 spaces respectively.