Python文本游戏中if字符串包含判断返回False的问题及解决
问题原因与解决方法
为什么判断不成立?
if command in directions是检查整个输入字符串是否完整存在于directions列表中。比如你的directions列表是["North", "South", "East", "West"]:
- 输入
"South"时,整个字符串和列表中的元素完全匹配,返回True; - 输入
"Go South"时,这个完整字符串不在列表里,所以返回False——Python不会自动从字符串中提取子串去匹配列表元素。
修改方案
方案1:拆分输入提取方向词
把输入按空格拆分成单词,遍历检查是否有单词属于directions:
# 假设已定义directions = ["North", "South", "East", "West"] command = input("输入命令:").strip() words = command.split() target_dir = None for word in words: if word in directions: target_dir = word break if target_dir: # 这里写你的移动逻辑,比如根据target_dir更新当前房间 print(f"向{target_dir}移动") else: print("无效命令")
方案2:适配固定命令格式(如"Go + 方向")
如果用户输入大概率是"Go 方向"的格式,可以针对性处理,同时兼容单个方向词的情况:
command = input("输入命令:").strip() if command.startswith("Go "): direction = command[3:] if direction in directions: print(f"向{direction}移动") else: print("无效的方向") elif command in directions: print(f"向{command}移动") else: print("无效命令")
可选优化:忽略大小写匹配
为了提升用户体验,允许输入小写或混合大小写的命令,比如"go south"也能识别:
command = input("输入命令:").strip().lower() # 把方向列表也转成小写用于匹配 directions_lower = [d.lower() for d in directions] words = command.split() target_dir = None for word in words: if word in directions_lower: # 找到对应的原方向词(保持大小写一致) target_dir = directions[directions_lower.index(word)] break if target_dir: print(f"向{target_dir}移动") else: print("无效命令")
内容的提问来源于stack exchange,提问作者LaLoba
相关产品推荐
相关产品推荐

