String expandtabs() Method in Python

String expandtabs() Method

The expandtabs() method in Python is used to replace tab characters ('\t') in a string with a specified number of spaces. It returns a new string with tab characters expanded into spaces based on the provided tab size.Here's the syntax of the expandtabs() method:

string.expandtabs(tabsize)

Parameters:

  • tabsize: The number of spaces to replace each tab character ('\t') in the original string. It is a required parameter, and you need to specify the desired tab size.

Example:

# Example string with tab characters
original_string = "Hello\tworld!\t\tPython"

# Expanding tab characters using tab size 4
expanded_string = original_string.expandtabs(4)

print("Original String:")
print(original_string)

print("\nExpanded String:")
print(expanded_string)

Output:

Original String:
Hello   world!      Python

Expanded String:
Hello   world!      Python

In this example, we used the expandtabs() method to replace tab characters in the original string with 4 spaces. The resulting expanded_string shows that each '\t' was replaced by four spaces, making the text more readable and preserving the tabular structure.

The expandtabs() method is useful when you want to format text containing tabular data or simply control the indentation in a string by specifying the desired tab size.