Python 判断字符串中是否包含某个子字符串
在 Python 中,我们可以使用 in
关键字来判断一个字符串是否包含某个子字符串。这个方法非常简单且直观。
实例
# 定义一个字符串
main_string = "Hello, welcome to the world of Python programming."
# 定义要查找的子字符串
sub_string = "Python"
# 使用 in 关键字判断子字符串是否存在于主字符串中
if sub_string in main_string:
print(f"'{sub_string}' is found in the main string.")
else:
print(f"'{sub_string}' is not found in the main string.")
main_string = "Hello, welcome to the world of Python programming."
# 定义要查找的子字符串
sub_string = "Python"
# 使用 in 关键字判断子字符串是否存在于主字符串中
if sub_string in main_string:
print(f"'{sub_string}' is found in the main string.")
else:
print(f"'{sub_string}' is not found in the main string.")
代码解析:
main_string
是我们需要检查的主字符串。sub_string
是我们要查找的子字符串。- 使用
in
关键字来判断sub_string
是否存在于main_string
中。如果存在,则返回True
,否则返回False
。 - 根据判断结果,输出相应的信息。
输出结果:
'Python' is found in the main string.
点我分享笔记
笔记需要是本篇文章的内容扩展!文章投稿,可点击这里
注册邀请码获取方式
分享笔记前必须登录!
注册邀请码获取方式
-->