Python: removeprefix() and removesuffix()
Swastik Baranwal

Swastik Baranwal @delta456

About: Hi, I'm Swastik Baranwal, a software developer from New Delhi, India passionate about open-source contribution, Gopher, Pythoneer, Compiler Design and DevOps.

Location:
Delhi, India
Joined:
Oct 7, 2019

Python: removeprefix() and removesuffix()

Publish Date: Aug 18 '20
8 2

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.

Comments 2 total

  • John Doe
    John DoeFeb 4, 2021

    You said "In Python 3.9 which is scheduled in to be released in October 2021". Did you mean October 2020?

    • Swastik Baranwal
      Swastik BaranwalFeb 4, 2021

      I think I did a typo. My bad, I will update it, thanks!

Add comment