Open In App

expandtabs() method in Python

Improve
Improve
Like Article
Like
Save
Share
Report

Python String expandtabs() Method specifies the amount of space to be substituted with the “\t” symbol in the string.

Python String expandtabs() Method Syntax

Syntax : expandtabs(space_size)

Parameters

  • tabsize : Specifies the space that is to be replaced with the “\t” symbol in the string. By default the space is 8.

Return : Returns the modified string with tabs replaced by the space.

Python String expandtabs() Method Example

Example 1: expandtabs() With no Argument

Python3




string = "\t\tCenter\t\t"
print(string.expandtabs())


Output:

                Center          

Example 2: expandtabs() with different argument

Here, we have demonstrated multiple usages of the Python String expandtabs() Method with different tabsize parameter values.

Python3




# initializing string
string = "i\tlove\tgfg"
 
# using expandtabs to insert spacing
print("Modified string using default spacing: ", end ="")
print(string.expandtabs())
print()
 
# using expandtabs to insert spacing
print("Modified string using less spacing: ", end ="")
print(string.expandtabs(2))
print()
 
# using expandtabs to insert spacing
print("Modified string using more spacing: ", end ="")
print(string.expandtabs(12))
print()


Output:

Modified string using default spacing: i       love    gfg

Modified string using less spacing: i love  gfg

Modified string using more spacing: i           love        gfg

Exception :  Using expandtabs() on float or int types, raises AttributeError

TypeError when using expandtabs()

If we pass float or any other non-integer argument in “tabsize” parameter of Python String expandtabs() Method. It raises a TypeError.

Python3




string = "\tcenter\t"
print(string.expandtabs(1.1))


Output:

Traceback (most recent call last):
  File "/home/358ee0f95cc3b39382a3849ec716fc37.py", line 2, in <module>
    print(string.expandtabs(1.1))
TypeError: integer argument expected, got float

Applications : There are many possible applications where this can be used, such as text formatting or documentation, where user requirements keep on changing.



Last Updated : 18 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads