expandtabs()
methodThere are occasions when it is necessary to specify the amount of space to be left in a string.
The expandtabs()
method in Python’s library defines the amount of space to be substituted with the tab \t
symbol in the string.
expandtabs()
makes it easier and neater to add space in a string.
string_name.expandtabs(tabsize)
tabsize
is optional.
tabsize
: specifies the amount of space that will be replaced by the tab symbol \t
in the string.By default,
tabsize
is .
The expandtabs()
method returns the modified string with the tabs replaced by spaces.
The following code shows how to use the expandtabs()
method in Python.
The example below uses default spacing.
# Declaring variabletxt = "Welcome \t to \t Educative.io!"# Calling methodtxt2 = txt.expandtabs()# Display resultprint(txt2)
In the code above, we call expandtabs()
without specifying tabsize
. This automatically sets tabsize
to its default value.
In this example, we specify the tabsize
.
# Declaring stringtxt = "Welcome \t to \t Educative.io! Here is a shot on String expandtabs() in python "# using expandtabs to insert spacingprint("The modified string using less spacing: "+ txt.expandtabs(2))print("\r")# using expandtabs to insert spacingprint("The modified string using more spacing: "+ txt.expandtabs(12))print("\r")
In the code above, we call expandtabs()
with the tabsize
argument.
Remember, the default tabsize
is , and the compiler uses the default if tabsize
is not specified.
So, when compared to the default tabsize
, txt.expandtabs(2)
will insert less spacing and txt.expandtabs(12)
will insert more spacing in the txt
string.