Python 3 Strings | expandtabs () method



Sometimes it is necessary to specify space on a line, but the amount of free space is uncertain and depends on the environment and conditions. In these cases, changing the line over and over again is a tedious task. Hence, python has a “ expandtabs () ” in its library, which determines the amount of space that should be replaced with “/ t” in a line.

Syntax: expandtabs (space_size)

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

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

Code # 1: Code for demo extended tables ()

# Python3 demo code
# working with extensions ()

 
# initializing string

str = "i love gfg"

 
# using the space insertion extension

print ( "Modified string using default spacing:" , end =   "")

print ( str . expandtabs ())

 

print ( "" )

  
# using an extension to insert spaces

print ( "Modified string using less spacing:" , end = "")

print ( str . expandtabs ( 2 ))

 

print ( "" )

 
# using a space insertion extension

print ( "Modified string using more spacing:" , end = "")

print ( str . expandtabs ( 12 ))

 

print ( " " )

Output:

 Modified string using default spacing: i love gfg Modified string using less spacing: i love gfg Modifi ed string using more spacing: i love gfg 

Exception:
The exception with this method is that it does not accept a floating point number if we want to determine the exact precision of the space required.

Code # 2: Code to demonstrate exclusion from extended tables ()

# Python3 demo code
# extended tables exception ()

  
# initialization string

st = " i love gfg "

  
# use the space insertion extension

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 are constantly changing.