PYTHON

Using Python to removing prefixes and suffixes


TIL: Using Python to removing prefixes and suffixes















Daniel Roy Greenfeld

About | Articles | Books | Jobs | Tags | Search

How did I miss these functions getting added to Python?

Starting in Python 3.9, `s.removeprefix()` and `s.removesuffix()` were added as `str` built-ins. Which easily covers all the versions of Python I currently support.

## Usage for `removeprefix()`:

“`python
>>> ‘Spam, Spam’.removeprefix(‘Spam’)
‘, Spam’
>>> ‘Spam, Spam’.removeprefix(‘This is not in the prefix’)
‘Spam, Spam’
“`

## Usage for `removesuffix()`:

“`python
>>> ‘Spam, Spam’.removesuffix(‘Spam’)
‘Spam, ‘
>>> ‘Spam, Spam’.removesuffix(‘This is not in the suffix’)
‘Spam, Spam’
“`

Today I Learned

Tags: TIL python

← Back to all articles


LinkedIn | Twitter | Mastodon | Feeds: All, Python, TIL

All rights reserved 2024, Daniel Roy Greenfeld



Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button