Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removesuffix returns error 'str' object has no attribute 'removesuffix' [duplicate]

Tags:

python

string

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?

like image 968
Random Studios Avatar asked Sep 10 '25 18:09

Random Studios


1 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
like image 119
crcvd Avatar answered Sep 12 '25 11:09

crcvd