在 Python 中将转义字符转换为 utf

问题描述

python 有没有优雅的方法将“test\207\128”转换为“testπ”?

我的问题源于在 Linux 上使用 avahi-browse,它有一个 -p 标志以易于解析的格式输出信息。然而问题是它输出非字母数字字符作为转义序列。因此,发布为“name#id”的服务会被 avahi-browse 输出为“name\035id”。这可以通过在 \ 上拆分、删除前导零并使用 chr(35) 来恢复 # 来解决。此解决方案中断了多字节 utf 字符,例如“π”,输出为“\207\128”。

解决方法

您拥有的输入字符串是 UTF-8 字符串的编码,其格式是 Python 本身无法处理的。这意味着您需要编写一个简单的解码器,然后使用 Python 将 UTF-8 字符串转换为字符串对象:

import re
value = r"test\207\128"
# First off turn this into a byte array,since it's not a unicode string
value = value.encode("utf-8")
# Now replace any "\###" with a byte character based off
# the decimal number captured
value = re.sub(b"\\\\([0-9]{3})",lambda m: bytes([int(m.group(1))]),value)
# And now that we have a normal UTF-8 string,decode it back to a string
value = value.decode("utf-8")
print(value)
# Outputs: testπ