我如何在 Python 3 中进行 .decode('string-escape')?

新手上路,请多包涵

我有一些需要取消转义的转义字符串。我想用 Python 来做这件事。

例如,在 Python 2.7 中我可以这样做:

 >>> "\\123omething special".decode('string-escape')
'Something special'
>>>

我如何在 Python 3 中做到这一点?这不起作用:

 >>> 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

并将其变成:

 "support@psiloc.com"

完成转换后,我将检查我拥有的字符串是以 UTF-8 还是 UTF-16 编码的。

原文由 vy32 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 933
2 个回答

如果你想要转义序列的 strstr 解码,那么输入和输出都是 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'

原文由 MestreLion 发布,翻译遵循 CC BY-SA 4.0 许可协议

你必须使用 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'

原文由 Martijn Pieters 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题