Python String expandtabs() Method
The expandtabs() function returns a new string with the "\t" tabs replaced by blank spaces. That is, the expandtabs() function specifies the amount of empty space to be replaced by the "\t" tabs in the string.
\t tabs default to 4 spaces when displaying a text string, but when the expandtabs() function is used each \t symbol will be converted to 8 spaces unless you specify the number of spaces in the tabsize argument.
How to formulate it like this:
expand tabs (tab size = 8)
tabsize: specifies the space in the string to be replaced by tabs “\t”. By default, 8 blank spaces.
Return value: Returns a new string with the "\t" tabs replaced with blank spaces
In the following example, we will use the "\t" symbol, where 4 spaces are placed by default
Example:
string1 = 'a\tb\tc'
string2 = 'aaaa\tbbbb\tcccc'
print(string1)
print(string2)
The output will be:
a b c
aaaa bbbb cccc
In the following example, we will use the expandtabs() function without an integer value for the tabsize argument.
Example:
string1 = 'a\tb\tc'
string2 =undefined 'aaaa\tbbbb\tcccc'
print(string1. expandtabs())
print(string2. expandtabs())
The output will be:
a b c
aaaa bbbb cccc
In the following example, we will use the expandtabs() function and insert an integer value into the tabsize argument. Where blank spaces will be placed according to the specified numerical value.
Example:
string1 = 'a\tb\tc'
string2 = 'aaaa\tbbbb\tcccc'
print(string1.expandtabs(12))
print(string2.expandtabs(20))
The output will be:
a b c
aaaa bbbb cccc
If the value we give to the tabsize argument does not represent an integer. We will get an error.
Example:
string = "this is\tstring example.\t"
print(string.expandtabs(2.3))
We will get the error:
raceback (most recent call last):
File "./prog.py", line 5, in <module>
TypeError: integer argument expected, got float
External sources:
Built-in functions - official Python documentation
If you have any questions or concerns, leave them in the comments
Tags
Python Python String string methods python python expandtabs method
Share page
About author
Ahmed Obaid
Hello, I am Ahmed Obaid, an Egyptian Arabic programmer. I would like to put my experiences learning Python on this site So that it will be a reference for you and me as well.
Sign up to leave a comment