Python String expandtabs() Method

Python String expandtabs() method returns a copy of the original string where all tab characters (\t) are replaced by one or more spaces, depending on the current column and the given tab size. The default tabsize is 8.

Syntax

string.expandtabs(size)

Parameters

size(optional): It is the size that specifies the number of spaces we want to give in place of the “\t” symbol.

Return Value

It returns the string in which space replaces the tabs.

Visual Representation of Passing the “size” parameter

Visual Representation of Python String expandtabs() Method

Example 1: How to Use String expandtabs() Method

string = "Hello\tI\tam\tat\twork."

#if you don't pass any argument then default will be 8.
print(string.expandtabs())

Output

Hello  I      am      at      work.

Example 2: Passing the “size” parameterVisual Representation of Passing the "size" parameter

string = "Hello\tI\tam\tat\twork."

print("Printing the string using parameter of size=2")
print(string.expandtabs(2))

print("Printing the string using parameter of size=4")
print(string.expandtabs(4))

Output

Printing the string using parameter of size=2
Hello  I am  at  work.
Printing the string using parameter of size=4
Hello   I   am   at   work.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.