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


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

示例

以下是此演示:

my_list = [4, 3.0, 'python', 'is', 'fun']
print("The list is :")
print(my_list)

key = 'fun'
print("The key is :")
print(key)

print("The result is :")
if key in my_list:
   print("The key is present in the list")
else:
   print("The key is not present in the list")

输出

The list is :
[4, 3.0, 'python', 'is', 'fun']
The key is :
fun
The result is :
The key is present in the list

说明

  • 定义了一个由整数和字符串组成的列表,并显示在控制台上。
  • 定义了 key 的值,并显示在控制台上。
  • 使用了'if'循环来检查 key 是否存在于列表中。
  • 如果存在,则结果显示在控制台上。

更新时间:2021 年 9 月 16 日

444 人查看

开启您的职业生涯

完成课程取得认证

开始
广告
© . All rights reserved.