Pyhotn 中编码的问题:'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)的错误

Python中字符串类型分为byte string 和 unicode string两种。

如果在python文件中指定编码方式为utf-8(#coding=utf-8),那么所有带中文的字符串都会被认为是utf-8编码的byte string(例如:mystr="你好"),但是在函数中所产生的字符串则被认为是unicode string。
        问题就出在这边,unicode string 和 byte string 是不可以混合使用的,一旦混合使用了,就会产生这样的错误。例如:
        self.response.out.write("你好"+self.request.get("argu"))

        其中,"你好"被认为是byte string,而self.request.get("argu")的返回值被认为是unicode string。由于预设的解码器是ascii,所以就不能识别中文byte string。然后就报错了。

以下有两个解决方法:
       1.将字符串全都转成byte string。
            self.response.out.write("你好"+self.request.get("argu").encode("utf-8"))
        2.将字符串全都转成unicode string。
           self.response.out.write(u"你好"+self.request.get("argu"))
            byte string转换成unicode string可以这样转unicode(unicodestring, "utf-8")

猜你喜欢

转载自blog.csdn.net/m0_37247144/article/details/79892616