2

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.

Community
  • 1
  • 1
Will
  • 4,299
  • 5
  • 32
  • 50
  • There are no literal backslashes to match in your strings. The *literal* contains the two-character sequence `\n` to *specify* a newline, but Python converts that to a single, literal linefeed character in the resulting `str` object. – chepner Dec 09 '16 at 21:28

1 Answers1

3

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
daniboy000
  • 1,069
  • 2
  • 16
  • 26