如何在Python中以不区分大小写的方式比较字符串?

我想使用简单的python代码将常规字符串的比较封装到存储库字符串中。我也想有能力在字典中查找值哈希字符串使用常规的python字符串。


当前回答

通常的方法是将字符串大写或小写,以便进行查找和比较。例如:

>>> "hello".upper() == "HELLO".upper()
True
>>> 

其他回答

您可以使用casefold()方法。casefold()方法在比较时忽略案例。

firstString = "Hi EVERYONE"
secondString = "Hi everyone"

if firstString.casefold() == secondString.casefold():
    print('The strings are equal.')
else:
    print('The strings are not equal.')

输出:

The strings are equal.

Unicode标准的第3.13节定义了无大小写的算法 匹配。

X.casefold() == Python 3中的Y.casefold()实现了“默认的无大小写匹配”(D144)。

案例折叠不会在所有实例中保存字符串的规范化,因此需要进行规范化('å' vs。“一个”)。D145引入了“规范无大小写匹配”:

import unicodedata

def NFD(text):
    return unicodedata.normalize('NFD', text)

def canonical_caseless(text):
    return NFD(NFD(text).casefold())

对于涉及U+0345字符的非常罕见的边缘情况,NFD()被调用两次。

例子:

>>> 'å'.casefold() == 'å'.casefold()
False
>>> canonical_caseless('å') == canonical_caseless('å')
True

此外,还有兼容无案例匹配(D146),如“mhz”(U+3392)和“标识符无案例匹配”,以简化和优化标识符的无案例匹配。

def insenStringCompare(s1, s2):
    """ Method that takes two strings and returns True or False, based
        on if they are equal, regardless of case."""
    try:
        return s1.lower() == s2.lower()
    except AttributeError:
        print "Please only pass strings into this method."
        print "You passed a %s and %s" % (s1.__class__, s2.__class__)

假设ASCII字符串:

string1 = 'Hello'
string2 = 'hello'

if string1.lower() == string2.lower():
    print("The strings are the same (case insensitive)")
else:
    print("The strings are NOT the same (case insensitive)")

从Python 3.3开始,casefold()是一个更好的选择:

string1 = 'Hello'
string2 = 'hello'

if string1.casefold() == string2.casefold():
    print("The strings are the same (case insensitive)")
else:
    print("The strings are NOT the same (case insensitive)")

如果您想要一个处理更复杂unicode比较的更全面的解决方案,请参阅其他答案。

使用Python 2,在每个字符串或Unicode对象上调用.lower()…

string1.lower() == string2.lower()

...大部分时间都有效,但在@tchrist所描述的情况下确实不起作用。

假设我们有一个名为unicode.txt的文件,其中包含两个字符串Σίσυφος和ΣΊΣΥΦΟΣ。使用Python 2:

>>> utf8_bytes = open("unicode.txt", 'r').read()
>>> print repr(utf8_bytes)
'\xce\xa3\xce\xaf\xcf\x83\xcf\x85\xcf\x86\xce\xbf\xcf\x82\n\xce\xa3\xce\x8a\xce\xa3\xce\xa5\xce\xa6\xce\x9f\xce\xa3\n'
>>> u = utf8_bytes.decode('utf8')
>>> print u
Σίσυφος
ΣΊΣΥΦΟΣ

>>> first, second = u.splitlines()
>>> print first.lower()
σίσυφος
>>> print second.lower()
σίσυφοσ
>>> first.lower() == second.lower()
False
>>> first.upper() == second.upper()
True

Σ字符有两种小写形式ς和Σ, .lower()不能区分大小写进行比较。

然而,从Python 3开始,这三种表单都将解析为ς,并且在两个字符串上调用lower()将正确工作:

>>> s = open('unicode.txt', encoding='utf8').read()
>>> print(s)
Σίσυφος
ΣΊΣΥΦΟΣ

>>> first, second = s.splitlines()
>>> print(first.lower())
σίσυφος
>>> print(second.lower())
σίσυφος
>>> first.lower() == second.lower()
True
>>> first.upper() == second.upper()
True

所以如果你关心边界情况,比如希腊语中的3 sigma,请使用python3。

(作为参考,Python 2.7.3和Python 3.3.0b1显示在上面的解释器打印输出中。)