Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

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

I have a string with tabs like this

'replace      tabs in       this string’

How do I replace the tabs in this string with multiple spaces in python?


1 Answer
Rajendra Dharmkar

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
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.