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

PythonServer Side ProgrammingProgramming

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
raja
Updated on 27-Sep-2019 07:41:00

Advertisements