如何在Python中以不区分大小写的方式比较字符串?
我希望使用简单且符合Python习惯的代码封装普通字符串与存储库字符串之间的比较。我还希望能够使用普通Python字符串在由字符串哈希的字典中查找值。
如何在Python中以不区分大小写的方式比较字符串?
我希望使用简单且符合Python习惯的代码封装普通字符串与存储库字符串之间的比较。我还希望能够使用普通Python字符串在由字符串哈希的字典中查找值。
from re import search, IGNORECASE
def is_string_match(word1, word2):
# Case insensitively function that checks if two words are the same
# word1: string
# word2: string | list
# if the word1 is in a list of words
if isinstance(word2, list):
for word in word2:
if search(rf'\b{word1}\b', word, IGNORECASE):
return True
return False
# if the word1 is same as word2
if search(rf'\b{word1}\b', word2, IGNORECASE):
return True
return False
is_match_word = is_string_match("Hello", "hELLO")
True
is_match_word = is_string_match("Hello", ["Bye", "hELLO", "@vagavela"])
True
is_match_word = is_string_match("Hello", "Bye")
False
考虑使用 FoldedCase 来自 jaraco.text:
>>> from jaraco.text import FoldedCase
>>> FoldedCase('Hello World') in ['hello world']
True
如果您想要一个不考虑大小写的文本键控字典,请使用jaraco.collections中的FoldedCaseKeyedDict:
>>> from jaraco.collections import FoldedCaseKeyedDict
>>> d = FoldedCaseKeyedDict()
>>> d['heLlo'] = 'world'
>>> list(d.keys()) == ['heLlo']
True
>>> d['hello'] == 'world'
True
>>> 'hello' in d
True
>>> 'HELLO' in d
True
在 str.contains() 中可以提到 case=False
data['Column_name'].str.contains('abcd', case=False)
这是另一个正则表达式,我在过去的一周里学会了爱恨交加,通常会导入(在这种情况下是)反映我的感觉的东西! 创建一个普通函数...要求输入,然后使用....something = re.compile(r'foo*|spam*', yes.I)...... re.I(下面的yes.I)与IGNORECASE相同,但你不能犯太多错误写它!
然后使用正则表达式搜索您的消息,但老实说,这应该是自己的几页,但重点是将foo或spam管道在一起并忽略大小写。 然后,如果找到任何一个,lost_n_found将显示其中之一。如果没有,则lost_n_found等于None。如果不等于none,则使用“return lost_n_found.lower()”返回用户输入的小写。
这使您可以更轻松地匹配任何可能区分大小写的内容。最后(NCS)代表“没人在意认真...!”或不区分大小写....无论哪个
如果有任何问题,请联系我。
import re as yes
def bar_or_spam():
message = raw_input("\nEnter FoO for BaR or SpaM for EgGs (NCS): ")
message_in_coconut = yes.compile(r'foo*|spam*', yes.I)
lost_n_found = message_in_coconut.search(message).group()
if lost_n_found != None:
return lost_n_found.lower()
else:
print ("Make tea not love")
return
whatz_for_breakfast = bar_or_spam()
if whatz_for_breakfast == foo:
print ("BaR")
elif whatz_for_breakfast == spam:
print ("EgGs")
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__)