简体   繁体   中英

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'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM