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

Python字典匹配异常:输入存在却返回None,求错误排查

问题根源与修复方案

嘿,这个问题我一眼就看出来啦!你遇到的问题出在sys.stdin.readline()的行为上——它会把你输入时按下的换行符(\n)也一并读进变量里。

举个实际的例子:当你输入“Iron Man”并按下回车后,name变量实际存储的内容是"Iron Man\n"(末尾多了个看不见的换行符),而你的字典里的键是"Iron Man",没有那个换行符,所以super_heroes.get(name)找不到对应的值,自然返回了None。

你可以自己加一行代码验证这个问题:

print(repr(name))  # 运行后会输出 'Iron Man\n'

两种简单的修复方法:

  • 方法一:给读入的内容加上strip()
    strip()方法会自动去掉字符串首尾的空白字符(包括换行符、空格、制表符等),修改后的代码如下:
import sys
super_heroes = {'Iron Man' : 'Tony Stark', 'Superman' : 'Clark Kent', 'Batman' : 'Bruce Wayne'}
print ('Who is your favorite Superhero?')
name = sys.stdin.readline().strip()  # 关键是这里加了.strip()
print ('Do you know that his real name is', super_heroes.get(name))
  • 方法二:用input()替代sys.stdin.readline()
    Python的内置函数input()会自动忽略输入末尾的换行符,用它更简单直接:
super_heroes = {'Iron Man' : 'Tony Stark', 'Superman' : 'Clark Kent', 'Batman' : 'Bruce Wayne'}
print ('Who is your favorite Superhero?')
name = input()  # 直接用input()读取用户输入
print ('Do you know that his real name is', super_heroes.get(name))

现在再输入“Iron Man”,就能正确输出对应的真实姓名“Tony Stark”啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:06:39