比较Python 2.7.5中的字符串和unicode

Kul*_*rul 9 python python-2.7 python-unicode

我想知道为什么当我做:

a = [u'k',u'?',u'?']
Run Code Online (Sandbox Code Playgroud)

然后键入:

'k' in a
Run Code Online (Sandbox Code Playgroud)

我得到了True,同时:

'?' in a
Run Code Online (Sandbox Code Playgroud)

会给我False吗?

这真的让我很头疼,似乎有人故意让这个让人发疯...

aIK*_*Kid 15

这是为什么?

在Python 2.x中,您无法将unicode直接与非ascii字符进行比较.这会引发警告:

Warning (from warnings module):
  File "__main__", line 1
UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
Run Code Online (Sandbox Code Playgroud)

但是,在Python 3.x中没有出现,因为所有字符串都是unicode对象.

解?

你可以使字符串unicode:

>>> u'ç' in a
True
Run Code Online (Sandbox Code Playgroud)

现在,您要比较两个unicode对象,而不是unicode和string.

或者在比较之前将两者转换为编码,例如utf-8:

>>> c = u"ç"
>>> u'ç'.encode('utf-8') == c.encode('utf-8')
True
Run Code Online (Sandbox Code Playgroud)

此外,要在程序中使用非ascii字符,您必须在文件顶部指定编码:

# -*- coding: utf-8 -*-

#the whole program
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!