Random Studios
Random Studios

Reputation: 415

removesuffix returns error 'str' object has no attribute 'removesuffix'

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?

Upvotes: 26

Views: 41261

Answers (1)

crcvd
crcvd

Reputation: 1535

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

Upvotes: 50

Related Questions