Python 判断字符串中是否包含某个子字符串

Document 对象参考手册 Python3 实例

在 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.")

代码解析:

  1. main_string 是我们需要检查的主字符串。
  2. sub_string 是我们要查找的子字符串。
  3. 使用 in 关键字来判断 sub_string 是否存在于 main_string 中。如果存在,则返回 True,否则返回 False
  4. 根据判断结果,输出相应的信息。

输出结果:

'Python' is found in the main string.

Document 对象参考手册 Python3 实例