How to treat \t as a regular string in python

python, python-2.7, replace, string

Solution

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
>>>

Problem

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.

Original source

Related problems