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

如何解决Python中字符串搜索时出现的substring not found错误

错误原因

substring not found报错直接来自password.index(user)这行的误用:

  • str.index()的作用是检索指定子串在当前字符串中的下标位置,要求入参必须是字符串类型,但你传入的user是用户名对应的整数下标,Python会默认把整数转成字符串去输入的密码里检索,根本找不到对应子串,直接触发报错
  • 逻辑完全偏离需求:你要做的是校验输入密码是否和该用户名绑定的密码一致,完全不需要调用字符串的index()方法

原有逻辑漏洞

你写的第一层校验if username in Usernames and password in Passwords本身就有问题:只要输入的用户名在列表里、密码也在列表里,不管两者是不是对应关系,都会进入内层判断,比如输入用户名John、密码xyz也能过第一层校验,完全不符合登录逻辑要求。

修复后代码

Usernames = [
    "John",
    "Mark"    
]
Passwords = [
    "abc",
    "xyz"
]
username = input("Username: ")
password = input("Password: ")
if username in Usernames:
    user_index = Usernames.index(username)
    if Passwords[user_index] == password:
        print("Logged In!")
    else:
        print("Username or password incorrect.")
else:
    print("User not found.")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 18:45:04