Let’s say we have a string:
sentence = 'I love when monkeys write'
When we run
sentence.rstrip('new york times'), as if we wanted to remove any case of “new york times” from the string, we would expect the string to go unchanged. After all, “new york times” is not mentioned anywhere in
sentence. Instead though, we get this:
sentence.rstrip('new york times')
'I love wh'
Unlike how one might guess based on their names, Python’s
rstrip and similar string methods don’t remove suffixes. Instead, they remove trailing characters in the list provided. And as it turns out, “New York Times” is an anagram of “monkeys write” (plus the “en” in “when”). Therefore all of the characters in the former get found in the latter.
From the documentation,
The chars argument is not a suffix; rather, all combinations of its values are stripped
What’s the “right” way to remove a suffix? The docs recommend str.removesuffix(). This is only implemented in Python 3.9 and above.