-2
print('345nov'.rstrip('nov'))

the code above prints what you would expect: 345

So why does print('345v'.rstrip('nov')) print the same thing. The string doesn't end with "nov". It only ends with "v". But rstrip() strips it all the same. Either way, how can I make it ignore this behavior and not strip anything unless the ending string matches it exactly.

Directory
  • 135
  • 1
  • 2
  • 10
  • 1
    Note that this behavior is mentioned in the [docs](https://docs.python.org/3/library/stdtypes.html#str.rstrip). – 0x5453 Mar 17 '20 at 20:58
  • A dedicated method for that purpose doesn't exist (yet) but there's a discussion on [python-ideas](https://mail.python.org/archives/list/python-ideas@python.org/thread/RJARZSUKCXRJIP42Z2YBBAEN5XA7KEC3/) whether to add one. – a_guest Mar 17 '20 at 20:59
  • Conceptually a duplicate of [the same question on `lstrip`](https://stackoverflow.com/questions/58840638/why-i-am-getting-these-different-outputs). – Jongware Mar 17 '20 at 21:02

3 Answers3

2

You get this behavior because rstrip() actually takes an iterable for its parameter. That means the string you place in ("nov") is interpreted as ['n', 'o', 'v']. This can be proved further by changing the order of the characters:

>>>"345nov".rstrip("nvo")
345
Robert Kearns
  • 1,631
  • 1
  • 8
  • 15
1

You can use endswith and index the string:

string = '345v'
suffix = 'nov'
if string.endswith(suffix):
    string = string[:-len(suffix)]
a_guest
  • 34,165
  • 12
  • 64
  • 118
0

I ended up doing something similar to @a_guest.

def rstrip(a, b):
    if a.endswith(b):
        return a[:-len(b)]
    return a
Directory
  • 135
  • 1
  • 2
  • 10