removesuffix返回错误“str”对象没有属性“removesuffix”

我正在尝试使用删除后缀删除文件名的 .png 部分

'x.png'.removesuffix('.png')

但它不断返回:

AttributeError: 'str' object has no attribute 'removesuffix'

我试过其他一些字符串函数,但我一直得到“str”对象没有属性“”。我该怎么做才能解决这个问题?

回答

你想做什么?

removesuffix是 3.9+ 中的方法str。在以前的版本中,str没有removesuffix属性:

dir(str)

如果您不使用3.9,有几种方法可以解决这个问题。在 中3.4+pathlib如果后缀是路径,您可以使用它来操作:

import pathlib

pathlib.Path("x.png").with_suffix("")

否则,根据文档:

def remove_suffix(input_string, suffix):
    if suffix and input_string.endswith(suffix):
        return input_string[:-len(suffix)]
    return input_string

  • Where's 3.6 coming from?

以上是removesuffix返回错误“str”对象没有属性“removesuffix”的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>