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:

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,则表示该字符串不存在于列表中。

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

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运算符来检查列表中是否存在字符串。 还有一个... 根据上 列表 的KEY1 , 筛选下 列表 的数据,也就是标黄的数据。数量不大的情况,一般就是遍历比较,逻辑简单,几行代码搞掂。 但如果 列表 达到万,或者百万、千万,那遍历效率就低了。 先构造测试的 列表 。 # 构造筛选目标 列表 ,确保KEY不重复 n1 = 30000 n1_set = set([random.randint(1,n1) for n in range(n1)]) n1 = len(n1_set) list1 = [['110. 查找 字符串 ,若找到则返回从0开始的下标值,若找不到返回-1. 2、index()方法 在 字符串 查找 字符串 第一次出现的位置,类似于find()方法,不过比find()方法更好的是,如果 查找 不到子 字符串 ,会抛出异常,而不是返回-1. 3、rfind()和rinde
之前通过比较的笨的方法,判断 列表 (list) 所有元素是否 包含 字符串 (string) ,后来发现可以用all()来判断, 查找 了一些资料,写出来发现很简单,下面分享一下代码。 1、判断 列表 (list) ,所有元素是否在集合(set) list_string = ['big', 'letters'] string_set = set(['hello', 'hi', 'big', 'cccc', 'letters', 'anotherword']) result = all([word in string_