In Python 3.9 which is scheduled in to be released in October 2020
has introduced two new string methods
There were a lot of confusions as people thought
str.rstrip() that it 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.
str.removeprefix(substring: string)is a method which returns a new string with the trimmed prefix if the
strstarts 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 the
strends with it else it will return the original string.
These functions were implemented in python/cpython#18939.
def removeprefix(self: str, prefix: str, /) -> str: if self.startswith(prefix): return self[len(prefix):] else: return self[:]
def removesuffix(self: str, suffix: str, /) -> str: if self.endswith(suffix): return self[:-len(suffix)] else: return self[:]
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!
Python is always evolving with the community needs and it will be most used language in the future.