# How to expand tabs in string to multiple spaces in Python?

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Pyhton has a method called replace in string class. It takes as input the string to be replaced and string to replace with. It is called on a string object. You can call this method to replace tabs by spaces in the following way:

print( 'replace     tabs in       this string'.replace('\t', ''))

OUTPUT

replace tabs in this string

The 're' module in python can also be used to get the same result using regexes. re.sub(regex_to_replace, regex_to_replace_with, string) can be used to replace the characters in string. For example,

import re
print(re.sub('\t', '', 'replace    tabs in       this string'))

OUTPUT

replace tabs in this string
Updated on 27-Sep-2019 07:41:00