expandtabs method of Python str class

The expandtabs() method replaces tab stops with spaces. The number of spaces is determined by the cursor position and tab size. The example Python program expands tab stops with spaces in multiple python string variants.

Str Updated 18 Nov 2019 1 min read

Method Name

expandtabs

Method Signature

expandtabs (tabsize=8);

Parameters

Tabsize – Number of spaces for each tab present in the string.

Return Value

A string that has the tab characters replaced with spaces as per the tabsize parameter.

Overview

  • Tab characters in a string are replaced with spaces based on the current column position and the tabsize parameter.
  • For example, if tabsize = 2, the string “Hello World\t” will be added with two spaces after removing the '\t' character. The string is grown till its length reaches the next multiple of tabsize. If tabsize=7, the number of spaces added after removing the '\t' character, is 4.

Example

python
# Example program that expands the tab characters into spaces

def demoExpand(text):

    textWithTabs    = text;

    textWithNoTabs  = textWithTabs.expandtabs(tabsize=7);

    print("String with tabs:")

    print(textWithTabs);

    print("String with tabs expanded into spaces:")

    print(textWithNoTabs);

    print("Space count:")

    print(textWithNoTabs.count(" "));

text = "Helloworld\t";

demoExpand(text);

text = "Hello\tworld\t";

demoExpand(text);

Output

Output
String with tabs:

Helloworld

String with tabs expanded into spaces:

Helloworld

Space count:

4

String with tabs:

Hello   world

String with tabs expanded into spaces:

Hello  world

Space count:

4