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

Python字符串单词查找函数输出多余None问题排查与修复

问题成因
  • 自定义的search函数未写显式返回值,Python对无显式return的函数会默认返回None。
  • 函数内部已经通过print语句输出了匹配结果,代码最后额外加的print(search(text,word))会把函数返回的None一并打印,最终输出就会在结果后多出现一个None。
  • 测试用例里的反斜杠是代码续行标记,实际运行输入内容时不需要输入这个反斜杠,否则会被当作普通字符读入字符串,可能影响匹配结果。
修改方法

两种写法都可以实现预期效果,根据编码习惯选一种即可:

  • 写法1:保留函数内的打印逻辑,删掉最外层包裹函数调用的print,直接执行函数:
def search(text, word):
    if word in text:
        print("Word found")
    else:
        print("Word not found")

text = str(input())
word = str(input())
search(text, word)
  • 写法2:把函数内的print改成return返回结果字符串,保留最外层的打印逻辑:
def search(text, word):
    if word in text:
        return "Word found"
    else:
        return "Word not found"

text = str(input())
word = str(input())
print(search(text, word))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 05:36:13