In Python, is it possible to escape newline characters when printing a string?

Tyler picture Tyler · Mar 13, 2013 · Viewed 79.1k times · Source

I want the newline \n to show up explicitly when printing a string retrieved from elsewhere. So if the string is 'abc\ndef' I don't want this to happen:

>>> print(line)
abc
def

but instead this:

>>> print(line)
abc\ndef

Is there a way to modify print, or modify the argument, or maybe another function entirely, to accomplish this?

Answer

mgilson picture mgilson · Mar 13, 2013

Just encode it with the 'string_escape' codec.

>>> print "foo\nbar".encode('string_escape')
foo\nbar

In python3, 'string_escape' has become unicode_escape. Additionally, we need to be a little more careful about bytes/unicode so it involves a decoding after the encoding:

>>> print("foo\nbar".encode("unicode_escape").decode("utf-8"))

unicode_escape reference