[英]how do I .decode('string-escape') in Python3?
我有一些需要转义的转义字符串。 我想在 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
>>>
我的目标是成为 abel 接受这样的字符串:
s\000u\000p\000p\000o\000r\000t\000@\000p\000s\000i\000l\000o\000c\000.\000c\000o\000m\000
并将其变成:
"support@psiloc.com"
完成转换后,我将探查我拥有的字符串是用 UTF-8 还是 UTF-16 编码的。
您必须改用unicode_escape
:
>>> b"\\123omething special".decode('unicode_escape')
如果您从str
对象开始(相当于 python 2.7 unicode),您需要先编码为字节,然后使用unicode_escape
解码。
如果您需要字节作为最终结果,则必须再次编码为合适的编码( .encode('latin1')
,如果您需要保留文字字节值;前 256 个 Unicode 代码点映射 1-on- 1)。
您的示例实际上是带有转义符的 UTF-16 数据。 从unicode_escape
解码,回到latin1
以保留字节,然后从utf-16-le
(UTF 16 little endian without BOM):
>>> value = b's\\000u\\000p\\000p\\000o\\000r\\000t\\000@\\000p\\000s\\000i\\000l\\000o\\000c\\000.\\000c\\000o\\000m\\000'
>>> value.decode('unicode_escape').encode('latin1') # convert to bytes
b's\x00u\x00p\x00p\x00o\x00r\x00t\x00@\x00p\x00s\x00i\x00l\x00o\x00c\x00.\x00c\x00o\x00m\x00'
>>> _.decode('utf-16-le') # decode from UTF-16-LE
'support@psiloc.com'
旧的“字符串转义”编解码器将字节串映射到字节串,关于如何处理此类编解码器存在很多争论,因此目前无法通过标准编码/解码接口使用它。
但是,代码仍然存在于 C-API 中(作为PyBytes_En/DecodeEscape
),并且它仍然通过未记录的codecs.escape_encode
和codecs.escape_decode
暴露给 Python。
>>> import codecs
>>> codecs.escape_decode(b"ab\\xff")
(b'ab\xff', 6)
>>> codecs.escape_encode(b"ab\xff")
(b'ab\\xff', 3)
这些函数返回转换后的bytes
对象,加上一个表示处理了多少字节的数字……你可以忽略后者。
>>> value = b's\\000u\\000p\\000p\\000o\\000r\\000t\\000@\\000p\\000s\\000i\\000l\\000o\\000c\\000.\\000c\\000o\\000m\\000'
>>> codecs.escape_decode(value)[0]
b's\x00u\x00p\x00p\x00o\x00r\x00t\x00@\x00p\x00s\x00i\x00l\x00o\x00c\x00.\x00c\x00o\x00m\x00'
如果你想str -to- str解码转义序列,那么输入和输出都是 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')
'support@psiloc.com'
你不能在字节字符串上使用unicode_escape
(或者更确切地说,你可以,但它并不总是像string_escape
在 Python 2 上那样返回相同的东西)——当心!
此函数使用正则表达式和自定义替换逻辑实现string_escape
。
def unescape(text):
regex = re.compile(b'\\\\(\\\\|[0-7]{1,3}|x.[0-9a-f]?|[\'"abfnrt]|.|$)')
def replace(m):
b = m.group(1)
if len(b) == 0:
raise ValueError("Invalid character escape: '\\'.")
i = b[0]
if i == 120:
v = int(b[1:], 16)
elif 48 <= i <= 55:
v = int(b, 8)
elif i == 34: return b'"'
elif i == 39: return b"'"
elif i == 92: return b'\\'
elif i == 97: return b'\a'
elif i == 98: return b'\b'
elif i == 102: return b'\f'
elif i == 110: return b'\n'
elif i == 114: return b'\r'
elif i == 116: return b'\t'
else:
s = b.decode('ascii')
raise UnicodeDecodeError(
'stringescape', text, m.start(), m.end(), "Invalid escape: %r" % s
)
return bytes((v, ))
result = regex.sub(replace, text)
py2
"\\123omething special".decode('string-escape')
py3
"\\123omething special".encode('utf-8').decode('unicode-escape')
至少在我的情况下,这是等效的:
Py2: my_input.decode('string_escape')
Py3: bytes(my_input.decode('unicode_escape'), 'latin1')
转换工具.py:
def string_escape(my_bytes):
return bytes(my_bytes.decode('unicode_escape'), 'latin1')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.