Pythonでリスト内の文字列を大文字小文字を区別せずに検索する方法はいくつかあります。
方法1: str.upper()
または str.lower()
を使用する
この方法では、リスト内の各文字列と検索したい文字列をすべて大文字または小文字に変換します。その後、in
演算子を使用して文字列がリスト内に存在するかどうかを確認します。
username = 'MICHAEL89'
if username.upper() in (name.upper() for name in USERNAMES):
print('The string is in the list')
else:
print('The string is not in the list')
方法2: str.casefold()
を使用する
str.casefold()
メソッドは、str.lower()
メソッドと同様に文字列を小文字に変換しますが、より強力です。これは、すべての文字列のケースの違いを取り除くことを目的としているためです。
if 'MICHAEL89'.casefold() in (name.casefold() for name in USERNAMES):
print('The string is in the list')
else:
print('The string is not in the list')
方法3: カスタムクラスを作成する
この方法では、大文字と小文字を区別しない比較を行うカスタムクラスを作成します。
class CaseInsensitively(object):
def __init__(self, s):
self.__s = s.lower()
def __hash__(self):
return hash(self.__s)
def __eq__(self, other):
try:
other = other.__s
except (TypeError, AttributeError):
try:
other = other.lower()
except:
pass
return self.__s == other
これらの方法を使用すれば、Pythonのリスト内で大文字小文字を区別せずに文字列を検索することが可能になります。