Expandtabs method of Python str class

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:

# 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:

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

 


Copyright 2024 © pythontic.com