迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 中检查字符串是否在列表中忽略大小写

作者:迹忆客 最近更新:2023/01/24 浏览次数:

要检查字符串是否在忽略大小写的列表中:

  1. 遍历列表并将每个字符串转换为小写。
  2. 将要检查的字符串转换为小写。
  3. 使用 in 运算符以不区分大小写的方式检查字符串是否在列表中。
my_str = 'apple'

my_list = ['APPLE', 'BANANA', 'KIWI']

if my_str.lower() in (item.lower() for item in my_list):
    # 👇️ this runs
    print('The string is in list')
else:
    print('The string is not in the list')

我们使用生成器表达式来遍历列表。

生成器表达式用于对每个元素执行某些操作或选择满足条件的元素子集。

在每次迭代中,我们使用 str.lower() 方法将当前字符串转换为小写。

my_list = ['APPLE', 'BANANA', 'KIWI']

# 👇️ ['apple', 'banana', 'kiwi']
print(list(item.lower() for item in my_list))

str.lower 方法返回字符串的副本,其中所有大小写字符都转换为小写。

该方法不会更改原始字符串,它会返回一个新字符串。 字符串在 Python 中是不可变的。

最后一步是将我们要检查的字符串转换为小写并使用 in 运算符。

my_str = 'apple'

my_list = ['APPLE', 'BANANA', 'KIWI']

if my_str.lower() in (item.lower() for item in my_list):
    # 👇️ this runs
    print('The string is in list')
else:
    print('The string is not in the list')

in 运算符测试成员资格。 例如,如果 xl 的成员,则 x in l 的计算结果为 True,否则计算结果为 False

两个字符串都必须是小写或大写才能执行不区分大小写的比较。

如果我们的列表包含不是字符串的项目,请在调用 lower() 方法之前使用 str() 函数将每个项目转换为字符串。

my_str = 'kiwi'

my_list = ['APPLE', 1, 'BANANA', 2, 'KIWI']

if my_str.lower() in (str(item).lower() for item in my_list):
    # 👇️ this runs
    print('The string is in list')
else:
    print('The string is not in the list')

lower() 方法是特定于字符串的,因此我们必须在使用之前将每个列表项转换为字符串。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便