Python 解码utf

Python decode utf

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

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

期待/data/

2F/ 个字符的十六进制数。 Python 具有 chr 功能,即 returns 一个由 十进制 数字表示的字符。

所以你需要在 %s 和 "decode" ("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%