PyCharm中Python代码TypeError:字符串无法用|实现或判断
修复字符串条件判断的TypeError错误
错误原因
你代码里的"show" | "display" in user_action写法有误:|是Python的按位或运算符,仅适用于整数等支持位运算的类型,不能用来连接字符串实现逻辑“或”判断,因此触发了TypeError。
正确实现方式
方式1:用or分开判断每个条件
这是最直观的写法,适合少量关键词的场景:
if "show" in user_action or "display" in user_action: with open("../files/todos.txt", "r") as file: todos = file.readlines()
方式2:用any()批量判断(推荐多关键词场景)
如果后续要加更多关键词,这种写法扩展性更强:
if any(keyword in user_action for keyword in ["show", "display"]): with open("../files/todos.txt", "r") as file: todos = file.readlines()
方式3:精确匹配场景(完全等于关键词时用)
如果你的需求是user_action必须完全等于"show"或"display"(而不是包含),可以直接判断是否在列表中:
if user_action in ["show", "display"]: with open("../files/todos.txt", "r") as file: todos = file.readlines()
内容的提问来源于stack exchange,提问作者DoesItMatter
相关产品推荐
相关产品推荐

