Python 在列表中查找字符串

我们可以使用Python‘in’运算符来检查列表中是否存在一个字符串,还有一个‘not in’运算符来检查列表中是否存在一个字符串。

1l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']
2
3# string in the list
4if 'A' in l1:
5    print('A is present in the list')
6
7# string not in the list
8if 'X' not in l1:
9    print('X is not present in the list')

输出:

1A is present in the list
2X is not present in the list

推荐阅读: Python f-strings让我们看看另一个例子,我们会要求用户输入字符串来检查列表。

1l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']
2s = input('Please enter a character A-Z:\n')
3
4if s in l1:
5    print(f'{s} is present in the list')
6else:
7    print(f'{s} is not present in the list')

输出:

1Please enter a character A-Z:
2A
3A is present in the list

Python 使用 count() 查找列表中的字符串

我们还可以使用 count() 函数来获取列表中的字符串的发生次数,如果其输出为 0,则意味着字符串不在列表中。

1l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']
2s = 'A'
3
4count = l1.count(s)
5if count > 0:
6    print(f'{s} is present in the list for {count} times.')

查找列表中的一个字符串的所有索引

没有内置的功能来获取列表中的一个字符串的所有索引的列表. 这里是一个简单的程序来获取列表中的所有索引的列表。

 1l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']
 2s = 'A'
 3matched_indexes = []
 4i = 0
 5length = len(l1)
 6
 7while i < length:
 8    if s == l1[i]:
 9        matched_indexes.append(i)
10    i += 1
11
12print(f'{s} is present in {l1} at indexes {matched_indexes}')

结果:A在指数中存在于 [‘A’, ‘B’, ‘C’, ‘D’, ‘A’, ‘A’, ‘C’ [0, 4, 5]

您可以从我们的 GitHub 存储库中查阅完整的 Python 脚本和更多 Python 示例。

Published At
Categories with 技术
Tagged with
comments powered by Disqus