What is String expandtabs() in Python?

The expandtabs() method

There are occasions when it is necessary to specify the amount of space to be left in a string.

The expandtabs() method in Python’s library defines the amount of space to be substituted with the tab \t symbol in the string.

expandtabs() makes it easier and neater to add space in a string.

Syntax


string_name.expandtabs(tabsize)

tabsize is optional.

Parameters

  • tabsize: specifies the amount of space that will be replaced by the tab symbol \t in the string.

By default, tabsize is 88.


Return value

The expandtabs() method returns the modified string with the tabs replaced by spaces.

Code

The following code shows how to use the expandtabs() method in Python.

Example 1

The example below uses default spacing.

# Declaring variable
txt = "Welcome \t to \t Educative.io!"
# Calling method
txt2 = txt.expandtabs()
# Display result
print(txt2)

Explanation 1

In the code above, we call expandtabs() without specifying tabsize. This automatically sets tabsize to its default value.

Example 2

In this example, we specify the tabsize.

# Declaring string
txt = "Welcome \t to \t Educative.io! Here is a shot on String expandtabs() in python "
# using expandtabs to insert spacing
print("The modified string using less spacing: "+ txt.expandtabs(2))
print("\r")
# using expandtabs to insert spacing
print("The modified string using more spacing: "+ txt.expandtabs(12))
print("\r")

Explanation 2

In the code above, we call expandtabs() with the tabsize argument.

Remember, the default tabsize is 88, and the compiler uses the default if tabsize is not specified.

So, when compared to the default tabsize, txt.expandtabs(2) will insert less spacing and txt.expandtabs(12) will insert more spacing in the txt string.

Free Resources