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"))