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

当需要在列表中查找字符串时,可以使用简单的“if”条件和“in”运算符。

示例

下面是相同的演示

my_list = [4, 3.0, 'python', 'is', 'fun']
print("名单是:")
print(my_list)

key = 'fun'
print("关键是:")
print(key)

print("结果是:")
if key in my_list:
   print("The key is present in the list")
else:
   print("The key is not present in the list")
输出结果
名单是:
[4, 3.0, 'python', 'is', 'fun']
关键是:
fun
结果是:
The key is present in the list

解释

  • 定义了一个整数和字符串列表并显示在控制台上。

  • 键的值已定义并显示在控制台上。

  • 'if' 循环用于检查键是否存在于列表中。

  • 如果是,则结果显示在控制台上。