Python编码问题

Python处理编码问题时总是出现如下错误:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)

 

出现这个问题时强烈推荐看下下面的博客,博客里面讲的非常清楚,也非常易懂。

http://in355hz.iteye.com/blog/1860787

 

总结下大致是:

python里有两种字符串类型,一种是str,一种是unicode,用引号定义的字符串就是str (如'str'),用u加引号定义的字符串就是unicode(如u'str'),如果不知道你的字符串属于那种类型,可以使用如下代码进行检测:

    string = 'hello'
    uni_str = u'hello'
    print isinstance(string, str)        #输出True
    print isinstance(string, unicode)    #输出False
    print isinstance(uni_str, str)     #输出False
    print isinstance(uni_str, unicode) #输出True

然后str与unicode的转换如下:

    string = 'hello'
    uni_str = u'hello'

    print isinstance(string.decode('utf8'), unicode)  #返回True
    print isinstance(uni_str.encode('utf8'), str)     #返回True

如果decode或者encode使用错了,如对str使用encode,对unicode使用decode就会报上面的错误。

 

posted @ 2018-01-30 19:18  风吹的心  阅读(174)  评论(0编辑  收藏  举报