我有一些转义字符串需要取消转义.我想用Python来做这个.

例如,在Python 2.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

把它变成:

"support@psiloc.com"

完成转换后,我将探索我拥有的字符串是用UTF-8还是UTF-16编码的.

推荐答案

如果您想要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'

Python-3.x相关问答推荐

无法使用诗词安装PyYaml

数据类对象列表的字典获取方法-在数据类列表中查找具有特定变量值的数据类

如何从包含SPAN文本的标记中获取链接

ValueError at /register/ 视图authenticate.views.register_user 未返回HttpResponse 对象.它返回 None 相反

计算文档中所有关键字(单词和多词)出现的频率

从 LeetCode 的 Python 解决方案类中理解关键字 self

如何转置和 Pandas DataFrame 并命名新列?

如何在 Python 中 cv2 的窗口标题上动态更新 FPS

Python 3.9.8 使用 Black 并导入 `typed_ast.ast3` 失败

在 Python 3 中使用 unittest.mock 修补 input()

创建日志(log)文件

Pandas 的 EMA 与股票的 EMA 不匹配?

如何在 Python 中计算两个包含字符串的列表的 Jaccard 相似度?

如果一个失败,如何取消收集中的所有剩余任务?

如何模拟 open(...).write() 而不会出现没有这样的文件或目录错误?

用于 unicode 大写单词的 Python 正则表达式

使用完整路径激活 conda 环境

调用 Python doctest 时如何启用省略号?

如何修复:cx_Oracle.DatabaseError:DPI-1047:找不到 64 位 Oracle 客户端库 - Python

在 Keras 中训练神经网络的零精度