最近开发一个功能,根据条件表达式过滤数据,其中用到了eval(条件字符串,字典)
发现一个现象:
>>> print u"campGrade in [ 'u51cfu8102u8425u6559u7ec3u4f53u9a8cu73ed', ]"
campGrade in [ '减脂体验班', ]
>>> print {'campGrade':u'u51cfu8102u8425u6559u7ec3u4f53u9a8cu73ed'}
{'campGrade': u'u51cfu8102u8425u6559u7ec3u4f53u9a8cu73ed'}
>>> print u'u51cfu8102u8425u6559u7ec3u4f53u9a8cu73ed'
减脂体验班
此时,若直接判断,会返回 False
>>> eval(u"campGrade in [ 'u51cfu8102u8425u6559u7ec3u4f53u9a8cu73ed', ]", {'campGrade':u'u51cfu8102u8425u6559u7ec3u4f53u9a8cu73ed'})
<string>:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False
字典中的unicode 需要转化成 str,如下:
>>> eval(u"campGrade in [ 'u51cfu8102u8425u6559u7ec3u4f53u9a8cu73ed', ]", {'campGrade':'减脂体验班'})
True
代码中可以添加.encode("utf-8"),将unocode转换成str形式!
>>> eval(u"campGrade in [ 'u51cfu8102u8425u6559u7ec3u4f53u9a8cu73ed', ]", {'campGrade':u'u51cfu8102u8425u6559u7ec3u4f53u9a8cu73ed'.encode("utf-8")})
True