Python在列表中查找字符串

时间:2020-02-23 14:42:42  来源:igfitidea点击:

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

l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']

# string in the list
if 'A' in l1:
  print('A is present in the list')

# string not 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

让我们看另一个示例,在该示例中,我们将要求用户输入字符串以检查列表。

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&#039;{s} is present in {l1} at indexes {matched_indexes}&#039;)