有个脑屁。但是我如何解码包含。
t = '%2Fdata%2F'
print(t.decode('utf8'))
'str' object has no attribute 'decode'期待/data/
发布于 2018-12-20 20:50:42
2F是/字符的十六进制数。Python具有chr函数,该函数通过十进制数字返回字符表示。
因此,您需要在chr(int("hex",16))) s和"decode“之后获得两个符号(”十六进制“->将它们转换为一个字符)。
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%https://stackoverflow.com/questions/53875266
复制相似问题