DEV Community

Swastik Baranwal
Swastik Baranwal

Posted on • Edited on

6 1

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.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (2)

Collapse
 
jdoe profile image
John Doe • Edited

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

Collapse
 
delta456 profile image
Swastik Baranwal

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay