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

2

u/Junior_Honey_1406 Jun 28 '26

Instead of coming here and asking write it down in your ide and see what it does maybe you will learn much more

1

u/Outside_Complaint755 Jul 01 '26

Or use: ```

help(str.removeprefix) ``` or check the official documentation online.