Jesvin Jose
Jesvin Jose

Reputation: 23088

C-style escaping in python

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

Answers (1)

falsetru
falsetru

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

Related Questions