Anentropic
Anentropic

Reputation: 33923

How do a print a backslash-escaped string to output '\n' in Python?

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.

Upvotes: 0

Views: 803

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295815

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'

Upvotes: 5

Related Questions