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

Python 3.8中使用find()查找子串未触发预期输出的原因咨询

问题原因及解决办法

你的代码没输出'find it'的核心原因是对str.find()方法的返回值理解有误:

  • str.find(sub)会返回子串sub在原字符串中首次出现的索引位置;如果找不到则返回-1。
  • 在你的代码里,str2 = "E2"刚好是str1的开头,所以str1.find(str2)返回0。
  • 而Python中0属于假值(Falsy),在if条件判断中会被视为False,因此不会执行print语句。

正确的写法有两种:

  1. 检查返回值是否不等于-1:
str1 = "E2ab"
str2 = "E2"
if str1.find(str2) != -1:
    print("find it")
  1. 更推荐使用in运算符,语义更清晰:
str1 = "E2ab"
str2 = "E2"
if str2 in str1:
    print("find it")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 08:52:03