如何转义(和取消转义)Python 中字符串的 C 转义字符(换行符、斜杠等)?
我猜 JSON.encode( string) 可以做到这一点,但是有更好的方法吗?
最佳答案
在 Python 2.7 中使用 str.encode('string-escape')
:
>>> '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('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'
关于python - python 中的 C 风格转义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17877982/