What is expandtabs() in Python?
Overview
If you want to specify the space in the string but you’re uncertain about the amount of space required, Python has an efficient way to handle white spaces between the strings. You can use the expandtabs() function for this purpose.
The expandtabs() function
expandtabs() is a built-in method that substitutes and expands the \t (tab character) between the string, with respect to the amount of white space provided as an argument.
Syntax
string.expandtabs(size)
Parameters
The syntax above represents the expandtabs() function. The function takes an optional parameter size that specifies the amount of space that should be between the strings.
The parameter is of type Integer and has a default size of .
Code
Example 1
In this example, we use the expandtabs() function without an argument.
sample_str = 'No\targ\twas\tpassed'result = sample_str.expandtabs()print(result)
Explanation
The sample code above demonstrates the use of the expandtabs() function without an argument.
-
The first tab character
\tis at position and has a default tabsizeof because no argument was passed to it. -
The function then replaces the tab character
\twith whitespace until the next tab stop. -
The number of whitespaces after
"No"will be because of the difference between the position of the first tab character and the first tab stop . -
The next tab stops are the multiples of the default tab
size. Hence, the next tab stops are , and so on. -
The position of the second and third tab characters are and , respectively. Consequently, the next tab stops are and .
-
Hence, there are spaces after
"arg"and spaces after"was".
Output
No arg was passed
Example 2
The example below uses the expandtabs() function with an argument.
sample_str = 'An\targ\twas\tpassed'result = sample_str.expandtabs(3)print(result)
Explanation
The sample code above demonstrates the use of the expandtabs() function with an argument.
-
The first tab character
\tis at position and has a tabsizeof . Thus, the tab stops will be a multiple of , e.g., , and so on. -
There will be whitespace after
"An"because of the positioned tab character at and a tab stop at position . -
While the positions of the second and third tab characters are and , respectively, the next tab stops will be at positions and .
-
Hence, there will be spaces after
"arg"and spaces after"was".
Output
An arg was passed
Conclusion
The expandtabs() method is very important in text-formatting where the user requirement keeps changing.