📜  Python程序在列表中查找字符串

📅  最后修改于: 2022-05-13 01:55:49.292000             🧑  作者: Mango

Python程序在列表中查找字符串

给定一个列表,任务是编写一个Python程序来检查列表是否包含特定的字符串。

例子:

方法一:使用 in运算符

in运算符可以方便地检查列表中是否存在特定的字符串/ 元素。

例子:

Python3
# assign list
l = [1, 2.0, 'have', 'a', 'geeky', 'day']
 
# assign string
s = 'geeky' 
 
# check if string is present in the list
if s in l:
    print(f'{s} is present in the list')
else:
    print(f'{s} is not present in the list')


Python3
# assign list
l = ['1', 1.0, 32, 'a', 'geeky', 'day']
 
# assign string
s = 'prime'
 
# check if string is present in list
if l.count(s) > 0:
    print(f'{s} is present in the list')
else:
    print(f'{s} is not present in the list')


Python3
# assign list
l = ['hello', 'geek', 'have', 'a', 'geeky', 'day']
 
# assign string
s = 'geek'
 
# list comprehension
compare = [i for i in l if s in l]
 
# check if sting is present in list
if len(compare) > 0:
    print(f'{s} is present in the list')
else:
    print(f'{s} is not present in the list')


Python3
# assign list
l = ['hello', 'geek', 'have', 'a', 'geeky', 'day']
 
# assign string
s = 'prime'
 
# check if string is present in list
if any(s in i for i in l):
    print(f'{s} is present in the list')
else:
    print(f'{s} is not present in the list')


输出:

geeky is present in the list

方法#2:使用count()函数

count()函数用于计算列表中特定字符串的出现次数。如果字符串的计数大于 0,则表示该字符串存在于列表中,否则该字符串不存在于列表中。

例子:

蟒蛇3

# assign list
l = ['1', 1.0, 32, 'a', 'geeky', 'day']
 
# assign string
s = 'prime'
 
# check if string is present in list
if l.count(s) > 0:
    print(f'{s} is present in the list')
else:
    print(f'{s} is not present in the list')

输出:

prime is not present in the list

方法#3:使用列表理解

列表推导式用于从其他可迭代对象(如元组、字符串、数组、列表等)创建新列表。它用于将迭代语句转换为公式。

例子:

蟒蛇3

# assign list
l = ['hello', 'geek', 'have', 'a', 'geeky', 'day']
 
# assign string
s = 'geek'
 
# list comprehension
compare = [i for i in l if s in l]
 
# check if sting is present in list
if len(compare) > 0:
    print(f'{s} is present in the list')
else:
    print(f'{s} is not present in the list')

输出:

geeky is present in the list

方法 #4:使用 any()函数

any()函数用于检查列表中元素的存在。就像 - 如果字符串中的任何元素与输入元素匹配,则打印该元素存在于列表中,否则打印该元素不存在于列表中。

例子:

蟒蛇3

# assign list
l = ['hello', 'geek', 'have', 'a', 'geeky', 'day']
 
# assign string
s = 'prime'
 
# check if string is present in list
if any(s in i for i in l):
    print(f'{s} is present in the list')
else:
    print(f'{s} is not present in the list')

输出:

prime is not present in the list