expandtabs() is a string method in Python. It replaces the tab characters ‘\t’ with whitespaces according to the specified number.
This method is defined as follows.
expandtabs() function takes one optional parameter, which specifies the number of whitespaces needed to replace the tab characters.
If no parameter is given, the default is set at 8.
The return value is the string with whitespaces in it.
In the code below, no argument is passed, so the whitespaces are set at 8, which is the default. With this, the tab stops are 8, 16, 24, and so on.
The first ‘\t’ character is present at index 3. The function replaces the ‘\t’ with whitespace till the next tab occurs. The number of spaces it adds is the difference between the tab size (here 8) and the position of character’\t’. So, five spaces are added after ‘Hey’.
Similarly, the function adds four spaces after ‘abcd’, which is the difference between the position of the second ‘\t’ character, i.e., 12, and the tab size, i.e., 8.
string = 'Hey\tabcd\t123' # default argument: 8 space = string.expandtabs() print("With default size:", space)
In the second example , the tab size is specified as 2. The tab stops become 2,4,6, and so on. Hence after ‘Hey’, the first tab stop is 4, and one space is added after it.
The second ‘\t’ character occurs at 10, and one space is added after it.
string = 'Hey\tabcde\t123' # with specified argument space = string.expandtabs(2) print("With tabsize 2:", space)
View all Courses