Python 3 Strings | expandtabs() method

expandtabs is a method specified in Strings in Python 3.

Sometimes, there is a need of specifying the space in the string, but amount of space to be left is uncertain and depending upon the environment and conditions. For these cases, need to modify the string again and again is a tedious task. Hence python in its library has “expandtabs()” which specifies the amount of space to be substituted with the “\t” symbol in the string.

Syntax : expandtabs(space_size)



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

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

 
Code #1 : Code to demonstrate expandtabs()

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# working of expandtabs()
  
# initializing string 
str = "i\tlove\tgfg"
  
# using expandtabs to insert spacing
print("Modified string using default spacing: ", end ="")
print(str.expandtabs())
  
print("\r")
  
# using expandtabs to insert spacing
print("Modified string using less spacing: ", end ="")
print(str.expandtabs(2))
  
print("\r")
  
# using expandtabs to insert spacing
print("Modified string using more spacing: ", end ="")
print(str.expandtabs(12))
  
print("\r")

chevron_right


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 :
The exception using this method is that it doesn’t accept the floating point number if we want to decide the exact precision of the space we require.

 
Code #2 : Code to demonstrate exception of expandtabs()

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# exception of expandtabs()
  
# initializing string 
st = "i\tlove\tgfg"
  
# using expandtabs to insert spacing
try:
    print("Modified string using default spacing: ")
    print(st.expandtabs(10.5))
      
except Exception as e:
    print("Error !! The error occurred is :")
    print(str(e))

chevron_right


Output:

Modified string using default spacing: 
Error !! The error occurred is :
integer argument expected, got float

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.