3

I need to remove \t from a string that is being written however when ever I do

str(contents).replace('\t', ' ')

it just removes all of the tabs. I understand this is because \t is how you write tabs but I want to know how to just treat it like a regular string.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Kprakash
  • 161
  • 2
  • 3
  • 9

1 Answers1

4

You can prefix the string with r and create a raw-string:

str(contents).replace(r'\t', ' ')

Raw-strings do not process escape sequences. Below is a demonstration:

>>> mystr = r'a\t\tb'  # Escape sequences are ignored
>>> print(mystr)
a\t\tb
>>> print(mystr.replace('\t', ' '))  # This replaces tab characters
a\t\tb
>>> print(mystr.replace(r'\t', ' '))  # This replaces the string '\t'
a  b
>>>