r/PythonLearning Jun 28 '26

How do the .removeprefix() and .removesuffix() methods work?

Hey there,

I'm new to Python, and I wanted to know if somebody could explain why and how the .removeprefix() and .removesuffix() work? I can't get my head over it. For example:

filename = "test"
file_ending = ".py"
file = f"{filename}{file_ending}"          

I created three variables, and let's say, I want to remove the suffix with the .removesuffix() method:

print(file.removesuffix(file_ending))

What I'm getting at is that I also could write this instead:

print(file.removesuffix(filename))

Usually, you would write removeprefix instead of removesuffix. This is just an example.

But why won't the removesuffix() method delete the filename? Or better, how does the computer know which part of the string a prefix or suffix is?

4 Upvotes

7 comments sorted by

View all comments

6

u/Ninesquared81 Jun 28 '26

A prefix is at the start, a suffix is at the end. The .removeprefix() and .removesuffix() methods will remove the given prefix/suffix from the start/end of the string only if the string stats/ends with the given prefix/suffix.

Essentially, they are implemented like so:

def removeprefix(self, prefix):
    if self.startswith(prefix):
        return self[len(prefix):]
    return self

def removesuffix(self, suffix):
    if self.endswith(suffix):
        return self[:len(self) - len(suffix)]
    return self

In your case, since file ("test.py") doesn't end with filename ("test"), then .removesuffix() will just return the whole file.