Pythonのin
演算子を使用して、リスト内に文字列が存在するかどうかを確認できます。リストに文字列が存在しないかどうかを確認するためのnot in
演算子もあります。
l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']
# リスト内の文字列
if 'A' in l1:
print('A is present in the list')
# リスト内の文字列ではありません
if 'X' not in l1:
print('X is not present in the list')
出力:
A is present in the list
X is not present in the list
お勧めの読み物:Python f-strings 別の例を見てみましょう。ここでは、ユーザーにリスト内の文字列を確認するように求めます。
l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']
s = input('Please enter a character A-Z:\n')
if s in l1:
print(f'{s} is present in the list')
else:
print(f'{s} is not present in the list')
出力:
Please enter a character A-Z:
A
A is present in the list
Pythonのcount()関数を使用してリスト内の文字列を見つける
count()関数を使用して、リスト内の文字列の出現回数を取得することもできます。出力が0の場合、その文字列はリスト内に存在しないことを意味します。
l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']
s = 'A'
count = l1.count(s)
if count > 0:
print(f'{s} is present in the list for {count} times.')
リスト内の文字列のすべてのインデックスを検索する
リスト内の文字列のすべてのインデックスのリストを取得する組み込み関数はありません。文字列がリスト内に存在するすべてのインデックスのリストを取得するための簡単なプログラムがこちらです。
l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']
s = 'A'
matched_indexes = []
i = 0
length = len(l1)
while i < length:
if s == l1[i]:
matched_indexes.append(i)
i += 1
print(f'{s} is present in {l1} at indexes {matched_indexes}')
出力:A is present in ['A', 'B', 'C', 'D', 'A', 'A', 'C'] at indexes [0, 4, 5]
GitHubリポジトリから完全なPythonスクリプトやさらなるPythonの例をチェックできます。
Source:
https://www.digitalocean.com/community/tutorials/python-find-string-in-list