Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.rstrip() is removing extra characters

Why does this statement remove the 'E' in 'PIPELINE':

In: 'PIPELINE_DEV'.rstrip('_DEV')
Out: 'PIPELIN'

But this statement does not remove the 'S':

In: 'PIPELINES_DEV'.rstrip('_DEV')
Out: 'PIPELINES'

This statement removes all of the E's at the end:

In: 'PIPELINEEEEEEEE_DEV'.rstrip('_DEV')
Out: 'PIPELIN'

When I turn the rstrip into 2 separate statements, it works fine:

In: 'PIPELINE_DEV'.rstrip('DEV').rstrip('_')
Out: 'PIPELINE'
like image 657
Nick Morgan Avatar asked Sep 14 '17 15:09

Nick Morgan


People also ask

What does Rstrip remove in Python?

The rstrip() method removes any trailing characters (characters at the end a string), space is the default trailing character to remove.

Does Rstrip remove newline?

rstrip('\n') . This will strip all newlines from the end of the string, not just one.


1 Answers

rstrip removes any trailing instances of the characters you supply from the string you apply it on until it finds something that doesn't match. This is stated in its documentation:

The chars argument is not a suffix; rather, all combinations of its values are stripped

Using rstrip('_DEV') it will remove _DEV from the string and then all Es (or 'D's or 'V's or '_'s) since those fall in the character set you've given (and no other character that isn't in that set has been found).

When you use .rstrip('DEV').rstrip('_') the first call to rstrip strips off 'DEV' and then stops because '_' isn't in the character set 'DEV'. '_' is then removed when the second call to rstrip is made.


Note that in Python >= 3.9, str.removesuffix was added in order to address this common misconception. Using removesuffix, you can supply a suffix string that is removed, if present, as a suffix of the string it is applied on.

Your example:

'PIPELINE_DEV'.removesuffix('_DEV')

would only remove the '_DEV' suffix.

like image 111
Dimitris Fasarakis Hilliard Avatar answered Oct 06 '22 01:10

Dimitris Fasarakis Hilliard