Python rstrip() works strange

Viewed 70

I faced problem which is an extremely strange for me.

str.rstrip([chars])

works really strange manner for me, in one example. (Or maybe I missed some important documentation part).

>>> 'car_id__isnull'.rstrip('__isnull')
>>> 'car_id' # works fine
>>> 'last_success__isnull'.rstrip('__isnull')
>>> 'last_succe' # I do not  understand why this happened ?

Thanks, in advance.

2 Answers

It happens because you have misunderstood what rstrip does. It strips all occurrences of any of the given characters from the right of the string.

Documentation is fabulous at describing these sorts of things.

Here's how rstrip works:

  1. Expects a string (more like a character sets) in the paranthesis

  2. If no value is given, it will remove whitespaces from the right of the string i.e. 'Tons of whitespace on the right '.rstrip()

    'Tones of whitespace on the right'

  3. If a value is given, then it removes every occurence of each and every character from the right of the given string, i.e. in your first example

    'car_id__isnull'.rstrip('__isnull')

It basically says "Ok, so the characters that i'm supposed to remove from the right are "_, i, s, n, u, l", so it does just that. And since the "car_id" ends with a "d" (not included in the parathesis of rstrip, it just ends there.

But in the second example,

'last_success__isnull'.rstrip('__isnull')

Since this time, it is supposed to remove the characters as "_, i, s, n, u, l", and of course it removes "__isnull" because it's included in the rstrip, but it it also removes the "ss" at the end of "last_success" as it is ending with the character "s" which is included in the to be removed characters list of rstrip.

I do hope this answer helps someone.

Related