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'
The rstrip() method removes any trailing characters (characters at the end a string), space is the default trailing character to remove.
rstrip('\n') . This will strip all newlines from the end of the string, not just one.
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 E
s (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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With