代码之家  ›  专栏  ›  技术社区  ›  Milad Khodabandehloo

如何用%作为分隔符字符串将UTF-16解码为python3中的原始格式?

  •  0
  • Milad Khodabandehloo  · 技术社区  · 6 年前

    编码 例如 '%u062a%u0633%u062a' 'تست' 波斯语。我不确定这些字符串的编码是什么。我怎样才能把它们转换成真正的形式 ‘_’ 是吗?

    2 回复  |  直到 6 年前
        1
  •  2
  •   blhsing    6 年前

    % \ unicode-escape

    s = b'%u062a%u0633%u062a'
    print(s.replace(b'%', b'\\').decode('unicode-escape'))
    
        2
  •  2
  •   Alex Fung    6 年前

    chr

    def convert_to_unicode(text):
        return_str = ''
        for character in text.split('%u'):
            if character:
                chr_code = int(character, 16)
                return_str += chr(chr_code)
        return return_str
    
    
    text = '%u062a%u0633%u062a'
    print(convert_to_unicode(text))
    

    تست
    

    another answer

    def convert_to_unicode(text: str):
        # Replace %.
        text = text.replace('%', '\\')
        # Escape unicode into character.
        text = text.encode().decode('unicode-escape')
        return text