Answer a question

I'm trying to remove the .png part of a filename using remove suffix

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

But it keeps returning:

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

I've tried some other string functions but I keep getting 'str' object has no attribute ' '. What should I do to fix this?

Answers

What are you trying to do?

removesuffix is a 3.9+ method in str. In previous versions, str doesn't have a removesuffix attribute:

dir(str)

If you're not using 3.9, there's a few ways to approach this. In 3.4+, you can use pathlib to manipulate the suffix if it's a path:

import pathlib

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

Otherwise, per the docs:

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

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐