2013-07-26 27 views
0

如何在python中爲字符串轉義(和unescape)C轉義字符(換行符,斜槓等)?在Python中C風格轉義

我想JSON.encode(字符串)這樣做,但有沒有更好的方法?

回答

3

使用str.encode('string-escape')在Python 2.7:

>>> '12\t34\n'.encode('string-escape') 
'12\\t34\\n' 
>>> '12\\t34\\n'.decode('string-escape') 
'12\t34\n' 

使用str.encode('unicode-escape')str.encode('unicode-escape').decode('utr-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' 
+0

請放置於相應的解碼 – aitchnyu

+0

@aitchnyu,添加代碼進行解碼。 – falsetru