Skip to main content

Python String expandtabs() Function

The String expandtabs() method replaces tab characters (\t) in a string with a specified number of spaces.

This method is particularly useful for formatting strings where you want to ensure consistent spacing, especially when dealing with text that includes tab characters.

By default, the expandtabs() method replaces each tab character with eight spaces, but you can specify a different number of spaces by passing an integer argument to the method.

Syntax

my_string.expandtabs(tabsize)

expandtabs() Parameters

Python String expandtabs() function parameters:

ParameterConditionDescription
tabsizeOptionalA number specifying the tabsize. Default tabsize is 8.

expandtabs() Return Value

Python String expandtabs() function returns a new string with all tab characters replaced by the specified number of spaces.

Examples

Example 1: Replace Tabs in a given String

Let's expand each tab character with spaces, using the default value for tabsize.

my_str1 = 'a\tb\tc'
my_str2 = 'aaa\tbbb\tccc'

print(my_str1.expandtabs()) # Output: a b c
print(my_str2.expandtabs()) # Output: aaa bbb ccc

output

a       b       c
aaa bbb ccc

Example 2: Replace Tabs in a given String with a different Tabsize

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

my_str = 'a\tb\tc'
print(my_str.expandtabs(2)) # Output: a b c
print(my_str.expandtabs(4)) # Output: a b c
print(my_str.expandtabs(6)) # Output: a b c

output

a b c
a b c
a b c