在Python 2中对转义字符进行编码的正确方法是什么,而不需要杀死Unicode? 您所在的位置:网站首页 python字符编码有哪些 在Python 2中对转义字符进行编码的正确方法是什么,而不需要杀死Unicode?

在Python 2中对转义字符进行编码的正确方法是什么,而不需要杀死Unicode?

2023-03-23 22:30| 来源: 网络整理| 查看: 265

在unicode数据中间用反斜杠转义ascii控制字符绝对是一件有用的事情,可以尝试完成。但是,这不仅仅是转义它们,当你想取回实际的字符数据时,还需要正确地解除转义它们。

在Python stdlib中应该有一种方法可以做到这一点,但是没有。我提交了一份错误报告。http://bugs.python.org/issue18679

但与此同时,这里有一个使用翻译和黑客技术的工作方法。

tm = dict((k, repr(chr(k))[1:-1]) for k in range(32)) tm[0] = r'\0' tm[7] = r'\a' tm[8] = r'\b' tm[11] = r'\v' tm[12] = r'\f' tm[ord('\\')] = '\\\\' b = u"Пример\n" c = b.translate(tm) print(c) ## results in: Пример\n

所有非反斜杠的单字母控制字符都将用\x##序列来转义,但如果你需要对这些字符做一些不同的处理,你的翻译矩阵可以做到这一点。这种方法是没有损失的,所以对我来说是有效的。

但把它弄回来也很麻烦,因为你不能只用翻译把字符序列翻译成单个字符。

d = c.encode('latin1', 'backslashreplace').decode('unicode_escape') print(d) ## result in Пример with trailing newline character

实际上,你必须使用latin1对映射到字节的字符进行单独编码,同时对latin1不知道的unicode字符进行反斜杠转义,以便unicode_escape编解码器能够以正确的方式重新组装所有字符。

更新:

所以我遇到一个情况,我需要这个东西在python2.7和python3.3中都能工作。我是这样做的(埋在一个_compat.py模块中)。

if isinstance(b"", str): byte_types = (str, bytes, bytearray) text_types = (unicode, ) def uton(x): return x.encode('utf-8', 'surrogateescape') def ntob(x): return x def ntou(x): return x.decode('utf-8', 'surrogateescape') def bton(x): return x else: byte_types = (bytes, bytearray) text_types = (str, ) def uton(x): return x def ntob(x): return x.encode('utf-8', 'surrogateescape') def ntou(x): return x def bton(x): return x.decode('utf-8', 'surrogateescape') escape_tm = dict((k, ntou(repr(chr(k))[1:-1])) for k in range(32)) escape_tm[0] = u'\0' escape_tm[7] = u'\a' escape_tm[8] = u'\b' escape_tm[11] = u'\v' escape_tm[12] = u'\f' escape_tm[ord('\\')] = u'\\\\' def escape_control(s): if isinstance(s, text_types): return s.translate(escape_tm) else: return s.decode('utf-8', 'surrogateescape').translate(escape_tm).encode('utf-8', 'surrogateescape') def unescape_control(s): if isinstance(s, text_types): return s.encode('latin1', 'backslashreplace').decode('unicode_escape') else: return s.decode('utf-8', 'surrogateescape').encode('latin1', 'backslashreplace').decode('unicode_escape').encode('utf-8', 'surrogateescape')


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有