python2.7 处理unicode和ascii字符串混用问题

python2.7默认的编码方式为ascii码,如下可以查询:

import sys
sys.getdefaultencoding()

如果直接在unicode和ascii字符串之间做计算、比较、连接,都会出错:

s = '您好'
u = u'您好'
s == u
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal

原因是:在进行同时包含 str 与 unicode 的运算时,Python 一律都把 str 转换成 unicode 再运算,当然,运算结果也都是 unicode。

正确的处理方法是:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
s = '您好'
u = u'您好'
s == u

结果会返回True

 

 

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

 

posted @ 2017-12-14 17:00  圆旭  阅读(1712)  评论(0编辑  收藏  举报