Python Find String in List

我们可以使用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在['A', 'B', 'C', 'D', 'A', 'A', 'C']中的索引为[0, 4, 5]

你可以从我们的GitHub代码库中查看完整的Python脚本和更多Python示例。

Source:
https://www.digitalocean.com/community/tutorials/python-find-string-in-list