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

Python TypeError: string indices must be integers错误修复求助

Python用户认证类注册报错修复方案

问题重现

编写的用户认证类Auth,首次执行注册正常,但第二次注册时触发TypeError: string indices must be integers错误,报错指向register方法中的邮箱检查逻辑。

原代码:

class Auth:
    def __init__(self):
        self.users = {}

    def register(self, username, email, password):
        if username in self.users:
            print("Username Already Exists")
        elif email in [u["email"] for u in self.users]:
            print("Email Already Exists")
        else:
            self.users[username] = {"email" : email,"password" : password}
            print("Account created SuccessFully")
            
    def login(self, email, password):
        for username, user_info in self.users.items():
            if user_info["email"] != email:
                print("Email Address Not Found")
            elif user_info["password"] != password:
                print("Incorrect Password")
            else:
                print("Login Successfull ✅")
                print("Welcome Back!")
                print(f"Hello Mr.{username}")
                print(f"Your Email Address Is {email}")

user = Auth()

执行流程:

  1. 首次执行user.register("Shahid Amin","aminShahid573@gmail.com","1234"),正常创建账号
  2. 再次执行user.register("Zeeshan Ali","HteZahid@gmail.com","12345"),触发报错

错误原因

直接遍历字典self.users时,迭代的是字典的键(即用户名字符串),而非存储用户信息的字典值。代码中[u["email"] for u in self.users]里的u是用户名字符串,尝试用字符串索引["email"]自然会触发类型错误。

修复方案

核心修复点

将邮箱检查逻辑中的遍历对象改为字典的值集合self.users.values(),这样u就会是存储用户信息的字典:

# 原错误代码
elif email in [u["email"] for u in self.users]:
# 修复后代码
elif email in [u["email"] for u in self.users.values()]:

更高效的优化写法

用生成器表达式替代列表推导式,无需生成完整的邮箱列表,找到匹配项就停止迭代,性能更优:

elif any(user["email"] == email for user in self.users.values()):

完整修复后代码

class Auth:
    def __init__(self):
        self.users = {}

    def register(self, username, email, password):
        if username in self.users:
            print("Username Already Exists")
        elif any(user["email"] == email for user in self.users.values()):
            print("Email Already Exists")
        else:
            self.users[username] = {"email": email, "password": password}
            print("Account created SuccessFully")
            
    def login(self, email, password):
        # 修复login方法的错误:遍历所有用户后未找到才提示邮箱不存在
        found = False
        for username, user_info in self.users.items():
            if user_info["email"] == email:
                found = True
                if user_info["password"] == password:
                    print("Login Successfull ✅")
                    print("Welcome Back!")
                    print(f"Hello Mr.{username}")
                    print(f"Your Email Address Is {email}")
                else:
                    print("Incorrect Password")
                break
        if not found:
            print("Email Address Not Found")

user = Auth()

额外优化说明

原login方法存在逻辑问题:每次遍历用户时,只要邮箱不匹配就打印"Email Address Not Found",会导致多次输出错误信息。修复后的代码先标记是否找到对应邮箱,遍历结束后统一处理未找到的情况,逻辑更严谨。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 19:17:49