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
相关产品推荐
相关产品推荐

