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.

Answer from jbg on Stack Overflow
Top answer
1 of 2
9

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.

2 of 2
2

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

๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_string_expandtabs.asp
Python String expandtabs() Method
Python Examples Python Compiler ... Python Interview Q&A Python Training ... The expandtabs() method sets the tab size to the specified number of whitespaces....
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-expandtabs-method
expandtabs() method in Python - GeeksforGeeks
July 11, 2025 - expandtabs() method in Python is used to replace all tab characters (\t) in a string with spaces. This method allows for customizable spacing, as we can specify the number of spaces for each tab.
๐ŸŒ
Python Reference
python-reference.readthedocs.io โ€บ en โ€บ latest โ€บ docs โ€บ str โ€บ expandtabs.html
expandtabs โ€” Python Reference (The Right Way) 0.1 documentation
If the character is a newline (n) or return (r), it is copied and the current column is reset to zero. Any other character is copied unchanged and the current column is incremented by one regardless of how the character is represented when printed. >>> "AA\tBB\n".expandtabs() 'AA BB\n' >>> ...
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ methods โ€บ string โ€บ expandtabs
Python String expandtabs()
The expandtabs() method returns a copy of string with all tab characters '\t' replaced with whitespace characters until the next multiple of tabsize parameter.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-use-expandtabs-in-python
How to use expandtabs() in Python?
The 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.
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ python โ€บ standard-library โ€บ str โ€บ expandtabs
Python str expandtabs() - Set Tab Size | Vultr Docs
December 11, 2024 - The expandtabs() method in Python is a string method used for setting the tab size in a given string. This method returns a copy of the string where all tab characters (\t) are replaced with the right amount of space, based on the tab size specified.
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ python โ€บ string_expandtabs.htm
Python String expandtabs() Method
The python string expandtabs() method returns a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size.
Find elsewhere
๐ŸŒ
AskPython
askpython.com โ€บ home โ€บ understanding python string expandtabs() function
Understanding Python String expandtabs() Function - AskPython
February 16, 2023 - The Python string expandtabs() function is used to deal with providing spaces between the strings at runtime. It replaces the โ€˜\tโ€™ character with the amount of space mentioned, default size being 8. The amount of size that replaces the โ€˜\tโ€™ ...
๐ŸŒ
DEV Community
dev.to โ€บ hyperkai โ€บ expandtabs-in-python-4l9j
expandtabs in Python - DEV Community
August 29, 2025 - v = "12\t1234\t1\t123\n1234\t1\t123\t12" print(v) # 12 1234 1 123 # 1234 1 123 12 print(v.expandtabs()) # 12 1234 1 123 # 1234 1 123 12 print(v.expandtabs(tabsize=0)) # 1212341123 # 1234112312 print(v.expandtabs(tabsize=1)) # 12 1234 1 123 # 1234 1 123 12 print(v.expandtabs(tabsize=2)) # 12 1234 1 123 # 1234 1 123 12 print(v.expandtabs(tabsize=3)) # 12 1234 1 123 # 1234 1 123 12 print(v.expandtabs(tabsize=4)) # 12 1234 1 123 # 1234 1 123 12 print(v.expandtabs(tabsize=5)) # 12 1234 1 123 # 1234 1 123 12 print(v.expandtabs(tabsize=6)) # 12 1234 1 123 # 1234 1 123 12 print(v.expandtabs(tabsize=7)) # 12 1234 1 123 # 1234 1 123 12
๐ŸŒ
Ahmedobaid
ahmedobaid.com โ€บ en โ€บ blog โ€บ python โ€บ python-expandtabs-method
Python String expandtabs() Method
Python String expand ... ... โ€‹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.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ what-is-expandtabs-in-python
What is expandtabs() in Python?
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. ... The syntax above represents the expandtabs() function.
๐ŸŒ
Javatpoint
javatpoint.com โ€บ python-string-expandtabs-method
Python String | expandtabs() method with Examples - Javatpoint
Python program to insert a new node at the middle of the Circular Linked List ยท Python program to sort the elements of the Circular Linked List ยท Python Function Programs ยท capitalize() casefold() center(width ,fillchar) count(string,begin,end) encode() endswith(suffix ,begin=0,end=len(string)) expandtabs(tabsize = 8) find(substring ,beginIndex, endIndex) format(value) index(subsring, beginIndex, endIndex) isalnum() isalpha() isdecimal() isdigit() isidentifier() islower() isnumeric() isprintable() isupper() isspace() istitle() isupper() join(seq) ljust(width[,fillchar]) lower() lstrip() par
๐ŸŒ
Learn By Example
learnbyexample.org โ€บ python-string-expandtabs-method
Python String expandtabs() Method - Learn By Example
April 20, 2020 - The expandtabs() method replaces each tab character โ€˜\tโ€˜ in a string with specified number of spaces (tabsize). By default, tabsize is 8.
๐ŸŒ
Dive into Python
diveintopython.org โ€บ home โ€บ functions & methods โ€บ string methods โ€บ expandtabs()
expandtabs() in Python - String Methods with Examples
The expandtabs() method in Python is a string method that replaces tab characters in a string with spaces. It allows you to specify the tab size as an optional parameter.
๐ŸŒ
YouTube
youtube.com โ€บ master code online
Python 3.7: Expandtabs String Method - YouTube
For a full written tutorial on Python's expandtabs string method visit https://www.mastercode.online If you have any questions visit https://www.mastercode.o...
Published: August 2, 2018
Views: 1K
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ expandtabs method
r/learnpython on Reddit: expandtabs method
June 25, 2024 -

hi everyone. im trying to learn python by youtube videos and the teacher showed some methods of string but for the rest of them he said we need to try and find out. now im at expandtabs. i understand what it does but i couldn't figure it out why the first space bigger than the second space. is there a rule for it?

string = 'abc\tdefghi\tjkl'

print(string.expandtabs())

result:

abc defghi jkl

๐ŸŒ
FresherBell
fresherbell.com โ€บ subtopic โ€บ python โ€บ expandtabs
expandtabs() - String Method - Python Tutorial | fresherbell.com
It will return a string, with all '\t' in a string will be replaced with whitespace characters of default size 8. we can also modify the tab size by specifying the size as a parameter in expandtabs() methods.