如何在Python中以不区分大小写的方式比较字符串?
我想使用简单的python代码将常规字符串的比较封装到存储库字符串中。我也想有能力在字典中查找值哈希字符串使用常规的python字符串。
如何在Python中以不区分大小写的方式比较字符串?
我想使用简单的python代码将常规字符串的比较封装到存储库字符串中。我也想有能力在字典中查找值哈希字符串使用常规的python字符串。
当前回答
以不区分大小写的方式比较字符串似乎无关紧要,但事实并非如此。我将使用Python 3,因为Python 2在这里还不发达。
首先要注意的是,Unicode中的大小写删除转换并不简单。存在text.lower() != text.upper().lower()的文本,例如"ß":
>>> "ß".lower()
'ß'
>>> "ß".upper().lower()
'ss'
但是让我们假设你想无案例地比较“BUSSE”和“Buße”。见鬼,您可能还想比较“BUSSE”和“BUẞE”相等——这是较新的大写形式。推荐使用casefold:
str.casefold () 返回字符串的大小写折叠副本。折叠的字符串可用于 caseless匹配。 大小写折叠类似于小写,但更激进,因为它是 用于删除字符串中的所有大小写区别。[…]
不要只使用lower。如果casefold不可用,执行.upper().lower()会有所帮助(但只是略有帮助)。
然后你应该考虑口音。如果你的字体渲染器很好,你可能认为“ê”==“ê”-但它不是:
>>> "ê" == "ê"
False
这是因为后者的重音是一个组合字符。
>>> import unicodedata
>>> [unicodedata.name(char) for char in "ê"]
['LATIN SMALL LETTER E WITH CIRCUMFLEX']
>>> [unicodedata.name(char) for char in "ê"]
['LATIN SMALL LETTER E', 'COMBINING CIRCUMFLEX ACCENT']
最简单的处理方法是unicodedata.normalize。您可能希望使用NFKD规范化,但请随意查看文档。然后有人会这么做
>>> unicodedata.normalize("NFKD", "ê") == unicodedata.normalize("NFKD", "ê")
True
最后,这里用函数表示:
import unicodedata
def normalize_caseless(text):
return unicodedata.normalize("NFKD", text.casefold())
def caseless_equal(left, right):
return normalize_caseless(left) == normalize_caseless(right)
其他回答
def search_specificword(key, stng):
key = key.lower()
stng = stng.lower()
flag_present = False
if stng.startswith(key+" "):
flag_present = True
symb = [',','.']
for i in symb:
if stng.find(" "+key+i) != -1:
flag_present = True
if key == stng:
flag_present = True
if stng.endswith(" "+key):
flag_present = True
if stng.find(" "+key+" ") != -1:
flag_present = True
print(flag_present)
return flag_present
输出: search_specificword(“经济适用房”,“欧洲经济适用房的核心”) 假
search_specificword(“经济适用房”,“经济适用房的核心,在欧洲”) 真正的
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__)
我找到了一个干净的解决方案,我正在使用一些固定的文件扩展名。
from pathlib import Path
class CaseInsitiveString(str):
def __eq__(self, __o: str) -> bool:
return self.casefold() == __o.casefold()
GZ = CaseInsitiveString(".gz")
ZIP = CaseInsitiveString(".zip")
TAR = CaseInsitiveString(".tar")
path = Path("/tmp/ALL_CAPS.TAR.GZ")
GZ in path.suffixes, ZIP in path.suffixes, TAR in path.suffixes, TAR == ".tAr"
# (True, False, True, True)
先转换成小写字母怎么样?你可以使用string.lower()。
使用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显示在上面的解释器打印输出中。)