我有一些转义字符串需要取消转义.我想用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相关问答推荐

如何绘制交叉验证的AUROC并找到最佳阈值?

将字符串转换为python日期时间时出错

从PYTHON中获取单行和多行的Rguar表达式

一起使用数据类和枚举

在一行中读写一个csv文件

将水平堆叠的数据排列成垂直

根据按不同列中的值分组的平均值划分 DataFrame

切片的Python复杂性与元组的星号相结合

裁剪复数以解决 exp 中的溢出错误

SqlAlchemy - 从 oracle db 中检索长文本

对齐文本文件中的列

二进制文件的 Python 3 和 base64 编码

简单的 get/post 请求在 python 3 中被阻止,但在 python 2 中没有

理解 Keras 的 ImageDataGenerator 类中的 `width_shift_range` 和 `height_shift_range` 参数

Python 3x 的最佳机器学习包?

Python 3.10 模式匹配 (PEP 634) - 字符串中的通配符

IronPython 3 支持?

在 Ubuntu 上为 Python3 安装 mod_wsgi

SQLAlchemy:如果不存在则创建模式

交错4个相同长度的python列表