我正在尝试使用删除后缀删除文件名的 .png 部分
'x.png'.removesuffix('.png')
但它不断返回:
AttributeError: 'str' object has no attribute 'removesuffix'
我试过其他一些字符串函数,但我一直得到“str”对象没有属性“”。我该怎么做才能解决这个问题?
你想做什么?
removesuffix是 3.9+ 中的方法str。在以前的版本中,str没有removesuffix属性:
dir(str)
Run Code Online (Sandbox Code Playgroud)
如果您不使用3.9,有几种方法可以解决这个问题。在 中3.4+,pathlib如果后缀是路径,您可以使用它来操作:
import pathlib
pathlib.Path("x.png").with_suffix("")
Run Code Online (Sandbox Code Playgroud)
否则,根据文档:
def remove_suffix(input_string, suffix):
if suffix and input_string.endswith(suffix):
return input_string[:-len(suffix)]
return input_string
Run Code Online (Sandbox Code Playgroud)