Python在列表中查找字符串

We can use Python in operator to check if a string is present in the list or not. There is also a not in operator to check if a string is not present in the list.

我们可以使用Python in运算符来检查列表中是否存在字符串。 还有一个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')

Output:

输出:

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

Recommended Reading: Python f-strings

推荐读物: Python f字符串

Let’s look at another example where we will ask the user to enter the string to check 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')

Output:

输出:

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

Python使用count()在列表中查找字符串 (Python Find String in List using count())

We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list.

我们还可以使用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.')

在列表中查找字符串的所有索引 (Finding all indexes of a string in the list)

There is no built-in function to get the list of all the indexes of a string in the list. Here is a simple program to get the list of all the indexes where the string is present in the list.

没有内置函数来获取列表中字符串的所有索引的列表。 这是一个简单的程序,用于获取列表中存在字符串的所有索引的列表。

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}')

Output: A is present in ['A', 'B', 'C', 'D', 'A', 'A', 'C'] at indexes [0, 4, 5]

输出: A is present in ['A', 'B', 'C', 'D', 'A', 'A', 'C'] at indexes [0, 4, 5]

GitHub Repository. GitHub存储库中检出完整的python脚本和更多Python示例。

翻译自: https://www.journaldev.com/23759/python-find-string-in-list

你可能感兴趣的:(字符串,列表,python,机器学习,java)