gpt4 book ai didi

python - 在 Python 2.7.5 中比较字符串和 unicode

转载 作者:太空狗 更新时间:2023-10-29 19:35:58 27 4
gpt4 key购买 nike

我想知道为什么当我做的时候:

a = [u'k',u'ę',u'ą']

然后输入:

'k' in a

我得到 True,同时:

'ę' in a

会给我 False 吗?

真是让我头疼,好像有人故意搞这个是为了让人抓狂...

最佳答案

这是为什么?

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

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

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

解决方案?

您可以将字符串设为 unicode:

>>> u'ç' in a
True

现在,您正在比较两个 unicode 对象,而不是 unicode 与字符串。

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

>>> c = u"ç"
>>> u'ç'.encode('utf-8') == c.encode('utf-8')
True

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

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

#the whole program

希望这对您有所帮助!

关于python - 在 Python 2.7.5 中比较字符串和 unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19967399/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com