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

Python中在match case语句内使用endswith()函数报错求助

Python match case 使用 endswith() 报错的原因及修复方案

你的代码存在几个明显问题,导致运行报错,下面逐个说明并给出修复方案:

错误点分析

  • 字符串方法调用错误:file.lower.strip() 写法错误,lower() 是字符串的方法,必须加括号才能调用,正确写法是 file.lower().strip()。
  • match case 语法使用错误:Python 的 match 语句是用来匹配变量或表达式的值,你直接写 match True 并在 case 后放表达式 file.endswith(".png"),不符合语法规则。如果要在 case 里判断条件,需要使用守卫(guard),即在 case _ 后面加 if 指定判断条件。
  • 语法冗余错误:print("it’s an image"): 末尾多了一个冒号,会导致语法错误,需要删除。

修复后的代码

file = input("File name: ")
file = file.lower().strip()
match file:
    case _ if file.endswith(".png"):
        print("it’s an image")
    case _ if file.endswith((".jpg", ".jpeg", ".gif")):
        print("it’s also an image")
    case _:
        print("unknown file type")

补充说明

  • match file 表示我们要匹配的是 file 变量的值
  • case _ 是通配符,匹配任意值,后面的 if 就是守卫条件,用来判断文件扩展名
  • 可以将多个扩展名合并成元组传给 endswith(),实现同时判断多种同类型文件格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 21:42:34