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

PythonEscapingNewline

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

Another way that you can stop python using escape characters is to use a raw string like this:

>>> print(r"abc\ndef")
abc\ndef

or

>>> string = "abc\ndef"
>>> print (repr(string))
>>> 'abc\ndef'

the only proplem with using repr() is that it puts your string in single quotes, it can be handy if you want to use a quote

Solution 3 - Python

Simplest method: str_object.replace("\n", "\\n")

The other methods are better if you want to show all escape characters, but if all you care about is newlines, just use a direct replace.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTylerView Question on Stackoverflow
Solution 1 - PythonmgilsonView Answer on Stackoverflow
Solution 2 - PythonPurityLakeView Answer on Stackoverflow
Solution 3 - PythonACEfanatic02View Answer on Stackoverflow