我喜欢用这个表达
if 'MICHAEL89' in USERNAMES:
...
其中USERNAMES是一个列表。
是否有任何方法来匹配不区分大小写的项目,或者我需要使用自定义方法?只是想知道是否需要为此编写额外的代码。
我喜欢用这个表达
if 'MICHAEL89' in USERNAMES:
...
其中USERNAMES是一个列表。
是否有任何方法来匹配不区分大小写的项目,或者我需要使用自定义方法?只是想知道是否需要为此编写额外的代码。
当前回答
我需要这个字典而不是列表,杨晨的解决方案是最优雅的情况下,所以我修改了一点:
class CaseInsensitiveDict(dict):
''' requests special dicts are case insensitive when using the in operator,
this implements a similar behaviour'''
def __contains__(self, name): # implements `in`
return name.casefold() in (n.casefold() for n in self.keys())
现在你可以像这样转换字典USERNAMESDICT = CaseInsensitiveDict(USERNAMESDICT)和使用if 'MICHAEL89'在USERNAMESDICT:
其他回答
这里有一种方法:
if string1.lower() in string2.lower():
...
为此,string1和string2对象的类型都必须是string。
我的5美分(错误的)
"".join([' a']).lower()
更新
哎呦,完全同意@jpp,我会把它作为一个糟糕做法的例子:(
我需要这个字典而不是列表,杨晨的解决方案是最优雅的情况下,所以我修改了一点:
class CaseInsensitiveDict(dict):
''' requests special dicts are case insensitive when using the in operator,
this implements a similar behaviour'''
def __contains__(self, name): # implements `in`
return name.casefold() in (n.casefold() for n in self.keys())
现在你可以像这样转换字典USERNAMESDICT = CaseInsensitiveDict(USERNAMESDICT)和使用if 'MICHAEL89'在USERNAMESDICT:
我会做一个包装,这样你就不会受到伤害了。最低限度,例如……:
class CaseInsensitively(object):
def __init__(self, s):
self.__s = s.lower()
def __hash__(self):
return hash(self.__s)
def __eq__(self, other):
# ensure proper comparison between instances of this class
try:
other = other.__s
except (TypeError, AttributeError):
try:
other = other.lower()
except:
pass
return self.__s == other
现在,如果caseinsensitive ('MICHAEL89')在whatever:应该按照要求行事(无论右边是列表、字典还是集合)。(它可能需要更多的努力来实现字符串包含的类似结果,避免在某些情况下涉及unicode的警告,等等)。
username = 'MICHAEL89'
if username.upper() in (name.upper() for name in USERNAMES):
...
另外:
if username.upper() in map(str.upper, USERNAMES):
...
或者,是的,您可以创建一个自定义方法。