expandtabs() method in Python
expandtabs is a method specified in Strings in Python 3.
Sometimes, there is a need of specifying the space in the string, but the amount of space to be left is uncertain and depending upon the environment and conditions. For these cases, the 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()
# 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" ) |
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 of 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()
# 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)) |
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 documentation where user requirements keep on changing.