Python: removeprefix() and removesuffix()

delta456

Swastik Baranwal

Posted on August 18, 2020

Python: removeprefix() and removesuffix()

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 the str 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 the str 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[:]
Enter fullscreen mode Exit fullscreen mode
  • removesuffix()
def removesuffix(self: str, suffix: str, /) -> str:
    if self.endswith(suffix):
        return self[:-len(suffix)]
    else:
        return self[:]
Enter fullscreen mode Exit fullscreen mode

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! 
Enter fullscreen mode Exit fullscreen mode

Conclusion

Python is always evolving with the community's needs and it will be the most used language in the future.

💖 💪 🙅 🚩
delta456
Swastik Baranwal

Posted on August 18, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related