Python: removeprefix() and removesuffix()
Swastik Baranwal
Posted on August 18, 2020
In Python 3.9 which is scheduled to be released in October 2020
has introduced two new string methods str.removeprefix()
and str.removesuffix()
respectively.
Why
There were a lot of confusion as people thought str.lstrip()
and str.rstrip()
that can be used to trim prefix and suffix but the parameter accepts a set of characters not the substring.
These methods are useful for trimming prefix/suffix and also make code short and readable.
Purpose
str.removeprefix(substring: string)
is a method which returns a new string with the trimmed prefix if thestr
starts with it else it will return the original string.str.removesuffix(substring: string)
is a method which returns a new string with the trimmed suffix if thestr
ends with it else it will return the original string.
Implementation
These functions were implemented in python/cpython#18939.
-
removepreifx()
def removeprefix(self: str, prefix: str, /) -> str:
if self.startswith(prefix):
return self[len(prefix):]
else:
return self[:]
-
removesuffix()
def removesuffix(self: str, suffix: str, /) -> str:
if self.endswith(suffix):
return self[:-len(suffix)]
else:
return self[:]
Usage
This shows the usage of the functions and the output of all the cases.
s = 'Hello World from Python 3.9!'
print(s.removeprefix('Hello World')) // from Python 3.9!
print(s.removeprefix('')) // Hello World from Python 3.9!
print(s.removesuffix('3.9!')) // Hello World from Python
print(s.removesuffix('Python')) // Hello World from Python 3.9!
Conclusion
Python is always evolving with the community's needs and it will be the most used language in the future.
Posted on August 18, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.