You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 判断文本含指定字符串时if条件语句运行异常问题

问题原因

你代码的错误在于判定逻辑用错了比对对象:Text是存储待检测内容的字符串变量,你直接拿它和布尔值True做相等/身份判断,和实际的子串包含判定结果没有关联。
你之前尝试的几种写法的问题:

  • if Text == True::非空字符串和True的相等判定结果为False,永远进入else分支
  • if Text is True::is是Python的身份判定运算符,字符串和布尔值True不是同一个内存对象,判定永远为假
  • if Text == "True":是判断字符串内容是否等于"True",和你要检测的子串"Python"完全无关

正确实现

直接将子串包含判定"Python" in Text作为if的判定条件即可,示例代码如下:

Text = "Python for beginners"
# 可以先打印判定结果验证
print("Python" in Text)

if "Python" in Text:
    print("Its there!")
else:
    print("its not there")

如果需要多次使用这个判定结果,也可以先把结果存为单独的布尔变量:

Text = "Python for beginners"
has_python = "Python" in Text
print(has_python)

if has_python:
    print("Its there!")
else:
    print("its not there")

内容的提问来源于stack exchange,提问作者Bernybernd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 02:00:01