[英]C-style escaping in python
How do I escape (and unescape) the C escaped characters( newlines, slashes etc) for a string in python?我如何转义(和取消转义)python 中字符串的 C 转义字符(换行符、斜杠等)?
I guess JSON.encode( string) does this, but is there a better way?我猜 JSON.encode(string) 可以做到这一点,但是有更好的方法吗?
Use str.encode('string-escape')
in Python 2.7:在 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'
Use str.encode('unicode-escape')
or str.encode('unicode-escape').decode('utf-8')
:使用
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.