Reputation: 23088
How do I escape (and unescape) the C escaped characters( newlines, slashes etc) for a string in python?
I guess JSON.encode( string) does this, but is there a better way?
Upvotes: 2
Views: 1236
Reputation: 369134
Use str.encode('string-escape')
in Python 2.7:
>>> '12\t34\n'.encode('string-escape')
'12\\t34\\n'
>>> '12\\t34\\n'.decode('string-escape')
'12\t34\n'
Use str.encode('unicode-escape')
or str.encode('unicode-escape').decode('utf-8')
:
>>> '12\t34\n'.encode('unicode-escape')
b'12\\t34\\n'
>>> b'12\\t34\\n'.decode('unicode-escape')
'12\t34\n'
>>> '12\t34\n'.encode('unicode-escape').decode('utf-8')
'12\\t34\\n'
>>> '12\\t34\\n'.encode('utf-8').decode('unicode-escape')
'12\t34\n'
Upvotes: 3