首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python解码

Python解码
EN

Stack Overflow用户
提问于 2018-12-20 20:00:14
回答 1查看 62关注 0票数 2

有个脑屁。但是我如何解码包含。

代码语言:javascript
复制
t = '%2Fdata%2F'
print(t.decode('utf8'))
'str' object has no attribute 'decode'

期待/data/

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-20 20:50:42

2F/字符的十六进制数。Python具有chr函数,该函数通过十进制数字返回字符表示。

因此,您需要在chr(int("hex",16))) s和"decode“之后获得两个符号(”十六进制“->将它们转换为一个字符)。

代码语言:javascript
复制
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字符,前面的代码会中断,请使用下面的代码。

代码语言:javascript
复制
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%
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53875266

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档