I am learning about Python and got to the expandtabs
command in Python.
This is the official definition in the docs:
string.expand
The expandtabs
method replaces the \t
with whitespace characters until the next multiple of tabsize parameter i.e., the next tab position.
for eg. take str.expandtabs(5)
'this (5)is(7)\tstring' so the '\t' is replaced with whitespace until index=10 and follwing string is moved forward. so you see 10-7=3 whitespaces. (**number in brackets are index numbers **)
eg2. str.expandtabs(4)
'this(4) is(7)\tstring' here '\t' replaces until index=8. so you see only one whitespace
str.expandtabs(n) is not equivalent to str.replace("\t", " " * n).
str.expandtabs(n)
keeps track of the current cursor position on each line, and replaces each tab character it finds with the number of spaces from the current cursor position to the next tab stop. The tab stops are taken to be every n
characters.
This is fundamental to the way tabs work, and is not specific to Python. See this answer to a related question for a good explanation of tab stops.
string.expandtabs(n)
is equivalent to:
def expandtabs(string, n):
result = ""
pos = 0
for char in string:
if char == "\t":
# instead of the tab character, append the
# number of spaces to the next tab stop
char = " " * (n - pos % n)
pos = 0
elif char == "\n":
pos = 0
else:
pos += 1
result += char
return result
And an example of use:
>>> input = "123\t12345\t1234\t1\n12\t1234\t123\t1"
>>> print(expandtabs(input, 10))
123 12345 1234 1
12 1234 123 1
Note how each tab character ("\t"
) has been replaced with the number of spaces that causes it to line up with the next tab stop. In this case, there is a tab stop every 10 characters because I supplied n=10
.