我有一些需要转义的转义字符串。我想用Python做到这一点。
例如,在python2.7中,我可以这样做:
>>> "\\123omething special".decode('string-escape')
'Something special'
>>>
如何在Python3中做到这一点?这不起作用:
>>> b"\\123omething special".decode('string-escape')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
LookupError: unknown encoding: string-escape
>>>
我的目标是成为一个像这样的字符串:
s\000u\000p\000p\000o\000r\000t\000@\000p\000s\000i\000l\000o\000c\000.\000c\000o\000m\000
并将其转换为:
"[email protected]"
进行转换后,我将探查我拥有的字符串是否以UTF-8或UTF-16编码。
如果您希望海峡至- 海峡转义序列的解码,所以输入和输出都是Unicode:
def string_escape(s, encoding='utf-8'):
return (s.encode('latin1') # To bytes, required by 'unicode-escape'
.decode('unicode-escape') # Perform the actual octal-escaping decode
.encode('latin1') # 1:1 mapping back to bytes
.decode(encoding)) # Decode original encoding
测试:
>>> string_escape('\\123omething special')
'Something special'
>>> string_escape(r's\000u\000p\000p\000o\000r\000t\000@'
r'\000p\000s\000i\000l\000o\000c\000.\000c\000o\000m\000',
'utf-16-le')
'[email protected]'
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句