0
In [4]: import re

In [5]: print(re.escape('\n'))
\


In [6]: print(re.escape(r'\n'))
\\n

In [7]: print(r'\n')
\n

In [8]: print('\n')


In [9]: print('\\n')
\n

The third example print(r'\n') gives the output I want (also the last example).

BUT the string I want to print is a variable that was not defined as a raw string.

Needless to say I cannot manually add backslashes to the string.

Anentropic
  • 32,188
  • 12
  • 99
  • 147
  • https://stackoverflow.com/questions/7262828/python-how-to-convert-string-literal-to-raw-string-literal See the fourth answer – Mangohero1 Nov 27 '17 at 15:49

1 Answers1

5

Use repr() to print a value as Python code:

print(repr('\n'))

...will emit:

'\n'

If you want to strip leading and trailing characters, then:

print(repr('\n')[1:-1])

...will emit only

\n

...but this is not futureproof (some strings may be emitted with different quoting, if not today, then in future implementations; including the literal quotes in output is thus the safe option).


Note that in a format string, you can use the !r modifier to indicate that you want repr() applied:

print('Value: {!r}'.format('\n'))

...will emit:

Value: '\n'
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • Nice one, thank you! I am happy with the quoted output. This also works in my actual case which is more like `print('wtf {}'.format(repr('\n')))` --> `wtf '\n'` – Anentropic Nov 27 '17 at 15:49
  • 1
    There are better answers in that case -- you can use the format string itself to indicate that you want `repr()` to be applied. See edit. – Charles Duffy Nov 27 '17 at 15:50