用unicode替换字符串中数字的pythonic方法

2024-09-28 23:38:03 发布

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

我正在寻找一个python代码,它将采用一个非unicode字符串,例如"ab <U0054><U0064>",并用它的unicode等价物替换它,即:u"ab \u0054\u0064"u"ab Td"

有没有一种比这个更像Python的写作方式?你知道吗

def replace_unicode(s):
    while True:
        i = s.find('<U')
        if i == -1:
            break
        s = s.replace(s[i:i+7], unichr(int(s[i+2:i+6], 16)))
    return s

Tags: 字符串代码trueabdef方式unicodefind
1条回答
网友
1楼 · 发布于 2024-09-28 23:38:03

这个避免了无限循环+中断,而是使用^{}

def replace_unicode(s):
    # helper function which returns the unicode char for a re match object
    def unirepl(m):
        return unichr(int(m.group(1), 16))

    return re.sub(r"<U([0-9a-fA-F]{4})>", unirepl, s)

相关问题 更多 >