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.

1

1 Answer 1

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'
Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.