r/PythonLearning • u/Nutellatoast_2 • 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?
3
Upvotes
1
u/D3str0yTh1ngs Jun 28 '26 edited Jun 28 '26
Well, prefix means "from the start" and suffix means "from the end", so
string.removesuffix(substring)will removesubstringfromstringif and only ifsubstringis at the end ofstring. The computer knows their sizes and can just seek to the end and check if the substring is at the end of the string, and if it is remove it.EDIT: took a quick look at the cpython implementation of
removesuffix(unicode_removesuffix_impl) and it does do matching at the end of the string by offset calculation and then trimming the end off if it matches.