【发布时间】: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
脑袋放屁。但是我如何解码包含的字符串。
t = '%2Fdata%2F'
print(t.decode('utf8'))
'str' object has no attribute 'decode'
期待/data/
【问题讨论】:
标签: python-3.x utf-8 decode encode
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"。
%FF 符号。我已经修好了。