Python String expandtabs() Method

By Lenin Mishra

If you prefer to watch Youtube videos over reading blogs, check out our video on Python strings here.

The expandtabs() method in Python, sets the tabsize to the specified number of characters for every occurence of \t. Default is 8.

Syntax of expandtabs() method

string.expandtabs(tabsize)

tabsize: A positive integer specifying the tabsize. 
         Default tabsize is 8

Tab positions occur every tabsize character. Default is 8, giving tab positions at columns 0, 8, 16 and so on.

Example

Code

str1 = "Pylenin\tloves\tPython"
print(str1)

# Using default value
str2 = str1.expandtabs(8)
print(str2)

str3 = str1.expandtabs(10)
print(str3)

Output

Pylenin	loves	Python
Pylenin loves   Python
Pylenin             loves               Python

Check out other commonly used Python string methods.

  1. How to create a string in Python?
  2. How to access characters in a Python string?
  3. How to replace characters in a string in Python?
  4. How to concatenate strings in Python?
  5. How to iterate through a string in Python?
  6. Check if a Substring is Present in a Given String in Python
  7. Escape sequences in Python String
  8. Python String Formatting - The Definitive Guide