gpt4 book ai didi

python - 如何取消转义系统名称?

转载 作者:行者123 更新时间:2023-12-02 03:32:03 24 4
gpt4 key购买 nike

Systemd 以这种方式记录了其在单元名称中转义非字母数字字符的主要规则:

any "/" character is replaced by "-", and all other characters which are not ASCII alphanumerics or "_" are replaced by C-style "\x2d" escapes.

还有一个转义的例子:

$ systemd-escape -u 'Hall\xc3\xb6chen\x2c\x20Meister'Hallöchen, Meister

(More info in the docs here and here)

Let's ignore the trivial replacement "/" -> "-". I'm trying to unescape systemd names in Python (without 3rd party libraries). Many solutions I tried did not work, they converted the two bytes UTF-8 "ö" to two characters.

Finally this seems to produce the correct answer:

>>> esc=r'Hall\xc3\xb6chen\x2c\x20Meister'
>>> esc.encode('latin-1').decode('unicode_escape').encode('latin-1').decode('utf-8')
'Hallöchen, Meister'

如您所见:str -> bytes -> str -> bytes -> str。可以以某种方式简化吗?

最佳答案

使用字节字符串 esc = b'...' 代替原始字符串esc = r'...',如 python3 示例所示:

>>> esc = b'Hall\xc3\xb6chen\x2c\x20Meister'
>>> esc.decode('utf-8')
'Hallöchen, Meister'

关于python - 如何取消转义系统名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59333183/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com