python3:将ascii字符转换为unicode转义字符

2024-05-20 22:04:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将ascii字符转换为unicode转义字符

示例: "&""\\u0026"

上下文:

我在输入中收到两个值,第一个是字符串,另一个是包含一些内容的原始字节。 在此之后,正则表达式中使用第一个字符串来捕获原始数据。你知道吗

teste = "teste's teste & teste" raw = '.... teste\'s teste \\u0026 teste",null,["here","here2"] ....'

在此之后,regex与第一个var teste一起使用,以获取var here中的here2raw中的here2单词,但是在第一个var中有一些像&have这样的字符时,他无法在raw中找到任何模式,因为在raw中var是unicode转义的。你知道吗

因此,我尝试将一些字符(如&)转换为unicode转义,但没有成功


Tags: 字符串示例内容原始数据raw字节herevar
1条回答
网友
1楼 · 发布于 2024-05-20 22:04:19

非常感谢,我会暂时解决这个问题:

def escape_word(word):
    whitelist = [" ", "'"] + list(string.ascii_letters)
    new_word = ""
    for _c in word:
        if _c in whitelist:
            new_word += _c
        else:
            new_word += "\\u%04x" % ord(_c)
    return new_word

直到我找到更好的解决办法。你知道吗

相关问题 更多 >