【问题标题】:Python decode utfPython 解码 utf
【发布时间】:2018-12-20 20:00:14
【问题描述】:

脑袋放屁。但是我如何解码包含的字符串。

t = '%2Fdata%2F'
print(t.decode('utf8'))
'str' object has no attribute 'decode'

期待/data/

【问题讨论】:

    标签: python-3.x utf-8 decode encode


    【解决方案1】:

    2F/ 字符的十六进制数。 Python 有 chr 函数,它返回一个由十进制数字表示的字符。

    所以你需要在%s 之后得到两个符号并将它们“解码”(“hex” -> chr(int("hex",16)))成一个字符。

    def decode_utf(string):
        for i in range(string.count("%")):
            tmp_index = string.index("%")
            hex_chr = string[tmp_index:tmp_index + 3]
            #replace only one characher at a time
            string = string.replace(hex_chr, chr(int(hex_chr[1:],16)),1)
        return string
    
    print(decode_utf("%2Fdata%2F"))
    #/data/
    print(decode_utf("hello%20world%21"))
    #hello world!
    

    编辑 1:

    如果有%25 字符,前面的代码会中断,请使用下面的代码。

    def decode_utf(string):
        utf_characters = []
        tmp_index = 0
    
        for i in range(string.count("%")):
            tmp_index = string.index("%",tmp_index)
            hex_chr = string[tmp_index:tmp_index + 3]
            if not hex_chr in utf_characters:
                utf_characters.append(hex_chr)
    
            tmp_index += 1
    
        for hex_chr in utf_characters:
            string = string.replace(hex_chr, chr(int(hex_chr[1:],16)))
    
        return string
    
    print(decode_utf("%25t%20e%21s%2ft%25"))
    #%t e!s/t%
    

    【讨论】:

    • 这是一个很好的编程练习。但在实际代码中,无需重新发明轮子——只需使用标准库:from urllib.parse import unquote; unquote('%2Fdata%2F') → 返回“/data/”。
    • 顺便说一句,您的解决方案因以下示例而中断:"%25data%25" - 它应该返回 "%data%",但实际上会产生 "Úta%25"
    • @lenz 我希望我在一年前就知道这个功能。谢谢(你的)信息。程序返回不正确的输出,因为它试图替换已被替换的 %FF 符号。我已经修好了。
    猜你喜欢
    • 1970-01-01
    • 2019-09-15
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 2020-08-02
    • 2020-07-17
    相关资源
    最近更新 更多