Related Tags

string
python
expandtabs()
communitycreator

What is String expandtabs() in Python?

Maria Elijah

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 $8$.

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 variabletxt = "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 spacingprint("The modified string using less spacing: "+  txt.expandtabs(2))print("\r")  # using expandtabs to insert spacingprint("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 $8$, 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.

RELATED TAGS

string
python
expandtabs()
communitycreator

CONTRIBUTOR

Maria Elijah