在 Python 中检查字符串中的某个字母
使用 in
运算符检查字符串中的某个字母,例如 if letter in string:
。 如果字母包含在字符串中, in
运算符将返回 True,否则返回 False。
my_str = 'jiyik.com'
# ✅ check if a certain letter is contained in a string
if 'k' in my_str:
# 👇️ this runs
print('The letter is contained in the string ✅')
else:
print('The letter is NOT contained in the string ✅')
# ----------------------------------------------
# ✅ check if a certain letter is NOT contained in a string
if 'z' not in my_str:
print('The letter is NOT contained in the string ✅')
else:
# 👇️ this runs
print('The letter is contained in the string ✅')
我们使用
in
运算符来检查字符串是否包含某个字母。
in 运算符测试成员资格。 例如,如果 x 是 s 的成员,则 x in s
的计算结果为 True,否则计算结果为 False。
my_str = 'www jiyik'
print('www' in my_str) # 👉️ True
print('another' in my_str) # 👉️ False
如果我们需要检查某个字母是否包含在忽略大小写的字符串中,请将两个字符串都转换为小写。
my_str = 'WWW JIYIK'
letter = 'k'
if letter.lower() in my_str.lower():
# 👇️ this runs
print('The letter is contained in the string')
else:
print('The letter is NOT contained in the string')
str.lower()
方法返回字符串的副本,其中所有大小写字符都转换为小写。
注意
:该方法不会更改原始字符串,而是返回一个新字符串。 字符串在 Python 中是不可变的。
将两个字符串都转换为小写或大写允许不区分大小写的成员资格测试。
如果我们需要检查某个字母是否不包含在字符串中,请使用 not in
运算符。
my_str = 'jiyik.com'
print('x' not in my_str) # 👉️ True
if 'x' not in my_str:
# 👇️ this runs
print('The letter is NOT contained in the string')
else:
print('The letter is contained in the string')
x not in s
返回x in s
的否定。
如果我们需要以不区分大小写的方式检查字符串中是否不包含该字母,请将两个字符串都转换为小写。
my_str = 'jiyik.com'
letter = 'X'
print(letter.lower() not in my_str.lower()) # 👉️ True
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。