美文网首页
python下一个转码的问题

python下一个转码的问题

作者: zchongr | 来源:发表于2015-09-07 16:59 被阅读109次

    我想把一个quoted的字符串经过unquote处理后,打印出来。被unquote处理后的字串应该是utf-8的,因此还需要按照utf-8再做一次解码,代码如下:

    import urllib

    import struct

    srcString = u'%E4%BD%A0%E5%A5%BD'        # 一个quoted的字串

    unquotedString = urllib.unquote(srcString)    # 经过unquote解码

    textString = unquotedString.decode('utf-8')    # 再按照utf-8decode之后打印

    print textString

    我会在textString = unquotedString.decode('utf-8')得到如下错误

    UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)

    编码错误是python中最难搞的问题,难道unquotedString不是utf-8编码的?我在unquotedString = urllib.unquote(srcString)这行之后插入了如下代码:

    print repr(unquotedString)

    得到结果为:

    u'\xe4\xbd\xa0\xe5\xa5\xbd'

    编码上完全是utf-8的……不过,为什么前面还有个u''?也就是说python把这个字符串当做unicode来处理,而其实是utf-8编码的。因此我猜测是不是urllib.unquote会保留所处理数据的类型,如果收到的是str,则转出来的就是str;如果收到的是unicode,则转出来的就是unicode?于是我把代码改成如下:

    import urllib

    import struct

    srcString = '%E4%BD%A0%E5%A5%BD'

    unquotedString = urllib.unquote(srcString)

    print repr(unquotedString)

    textString = unquotedString.decode('utf-8')

    print textString

    执行后得到结果:

    '\xe4\xbd\xa0\xe5\xa5\xbd'

    你好

    这样就正常了。看起来应该就是我之前的猜测,不应该把unicode交给urllib.unquote来处理,否则得到的是一个数据类型和编码不一致的结果,对这个结果再怎么转都会报错。

    另外,repr真是个好东西,它把一个对象转成人可以识别的字串。

    相关文章

      网友评论

          本文标题:python下一个转码的问题

          本文链接:https://www.haomeiwen.com/subject/ukjycttx.html