Reputation: 4469
In an attempt to answer this question, I managed to get the string to print
the escape characters by escaping the backslash.
When I try to generalize it to escape all escaped characters, it seems to do nothing:
>>> a = "word\nanother word\n\tthird word"
>>> a
'word\nanother word\n\tthird word'
>>> print a
word
another word
third word
>>> b = a.replace("\\", "\\\\")
>>> b
'word\nanother word\n\tthird word'
>>> print b
word
another word
third word
but this same method for specific escape characters, it does work:
>>> b = a.replace('\n', '\\n')
>>> print b
word\nanother word\n third word
>>> b
'word\\nanother word\\n\tthird word'
Is there a general way to achieve this? Should include \n
, \t
, \r
, etc.
Upvotes: 2
Views: 4628
Reputation: 1129
Define your string as raw using r'text', like in the code below:
a = r"word\nanother word\n\tthird word"
print(a)
word\nanother word\n\tthird word
b = "word\nanother word\n\tthird word"
print(b)
word
another word
third word
Upvotes: 3