【问题标题】:Converting escaped characters to utf in Python在 Python 中将转义字符转换为 utf
【发布时间】:2021-06-01 12:49:54
【问题描述】:
有没有一种优雅的方法可以在python中将“test\207\128”转换为“testπ”?
我的问题源于在 Linux 上使用 avahi-browse,它有一个 -p 标志以易于解析的格式输出信息。然而问题在于它将非字母数字字符输出为转义序列。因此,发布为“name#id”的服务会被 avahi-browse 输出为“name\035id”。这可以通过拆分 \、删除前导零并使用 chr(35) 来恢复 # 来解决。此解决方案会中断多字节 utf 字符,例如“π”,其输出为“\207\128”。
【问题讨论】:
标签:
python
utf-8
escaping
utf
avahi
【解决方案1】:
您拥有的输入字符串是 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π