Python String expandtabs() Method

Replaces tabs with spaces

Usage

The expandtabs() method replaces each tab character ‘\t‘ in a string with specified number of spaces (tabsize).

The default tabsize is 8 (tab stop at every eighth column).

Syntax

string.exandtabs(tabsize)

Python string expandtabs() method parameters
ParameterConditionDescription
tabsizeOptionalA number specifying the tabsize. Default tabsize is 8.

Basic Example

# Expand each tab character with spaces
S1 = 'a\tb\tc'
S2 = 'aaaa\tbbbb\tcccc'
print(S1.expandtabs())
print(S2.expandtabs())

# Prints a       b       c# Prints aaaa    bbbb    cccc

Specify Different Tabsize

The default tabsize is 8. To change the tabsize, specify optional tabsize parameter.

# Change the tabsize to 2, 4 and 6
S = 'a\tb\tc'
print(S.expandtabs(2))
print(S.expandtabs(4))
print(S.expandtabs(6))

# Prints a b c# Prints a   b   c# Prints a     b     c