In Python, is it possible to escape newline characters when printing a string?
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"))
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