Wednesday, February 4, 2026

strip, lstrip, rstrip can take away greater than anticipated · Ponderings of an Andy


Introduction

As a software program engineer, you’ve got cleaned your justifiable share of soiled strings. Eradicating main or trailing areas might be one of the crucial widespread issues performed to person enter.

In Python, that is performed with the .strip(), .lstrip() or .rstrip() features and usually seems to be like this:

>>> "     Andrew Wegner     ".decrease().strip()
'andrew wegner'
>>> "     Andrew Wegner     ".decrease().lstrip()
'andrew wegner     '
>>> "     Andrew Wegner     ".decrease().rstrip()
'     andrew wegner'

That is fairly easy and nothing surprising in happening.

Gotcha

The Gotcha is that every of those features take an inventory of characters that may be eliminated.

>>> "Andrew Wegner".decrease().rstrip(" wegner")
'and'

What occurred? Why wasn’t the outcome simply

Clarification

Learn line from the documentation once more, rigorously:

A listing of characters

Not an inventory of strings.

That is explicitly spelled out within the documentation, with an instance, displaying what the implications are. Nonetheless, for a brand new developer, it is surprising conduct. In any case, these seem to be intutive features.

The instance with my does the next:

  1. Receives an inventory of characters to take away. On this case it’s all letters in my final title, plus the area character: wegner
  2. Decrease case all letters within the enter string, leading to andrew wegner
  3. From the appropriate hand facet of the string, start eradicating characters which are within the enter record. Cease once you encounter a personality not within the record. On this case that implies that rengew wer are eliminated (proper to left) after which the d in andrew is encountered in order that rstrip perform stops.
  4. Return the remaining string of and

Resolution

Python has two features that can appropriately take away a string.removesuffix() and .removeprefix() for proper and left facet removals.

>>> "Andrew Wegner".decrease().removesuffix(" wegner")
'andrew'

These two features have been launched in Python 3.9 as a part of PEP-616. Within the PEP, it explicitly calls out the confusion customers have concerning the *strip() features and the way they behave. These two have been launched to permit the specified conduct.

One essential notice is that these two take away* features will solely take away at most one occasion of the string.

>>> "Andrew Wegner Wegner".decrease().removesuffix(" wegner")
'andrew wegner'

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles