The expandtabs( ) Function is used to set the size of the tab.
Let us see the below example using the tab escape character '\t'. We won't be using expandtabs( ) Function in this example.
x = "Hello\tMic" print(x)
In the above code , we have declared a String 'Hello\tMic' .
By default , a tab '\t' places '8' spaces. But if you look at the above diagram , tab '\t' placed only '3' spaces(i.e. Position '5' , '6' and '7').
That is because tab '\t' starts its count from its previous String.
i.e. In this case, the previous String of tab '\t' is 'Hello'. And the size of 'Hello' is '5'. And the tab '\t' is supposed to take '8' spaces. And since '5' locations are taken by 'Hello', rest '3' locations are filled with spaces.
Now, let us say you want to use the tab (i.e. '\t') and use it to put 2 spaces instead of 3.
Let us see with the below example.
x = "Hello\tMic" y = x.expandtabs(7) print(y)
In the above code, we have declared a String 'Hello\tMic'.
As we know, by default, a tab '\t' places '8' spaces. And we have used the 'x.expandtabs(7)' function to reserve '7' spaces for tab. Out of which 'Hello' occupied '5' spaces and rest '2' are left. That is filled by white spaces.
Similarly, if you want to have 4 spaces for tab. We can achieve it by the below way.
x = "Hello\tMic" y = x.expandtabs(9) print(y)
In the above code, we have declared a String 'Hello\tMic'.
Similarly, by default, a tab '\t' places '8' spaces. And we have used the 'x.expandtabs(7)' function to reserve '10' spaces for tab. Out of which 'Hello' occupied '5' spaces and rest '5' are left. That is filled by white spaces.