Alex Liebscher

Alex Liebscher

Oddities and Surprises: Unusual Behaviors in R and Python

Questioning the developers of our favorite languages

This document is a collection of unexpected behaviors in R and Python. It’s inspired by Python Oddities and Python’s horror show. I will add to it over time.

Python

String Strip

Behavior

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'

Explanation

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.

Nested For Loops

Behavior

Explanation

https://peps.python.org/pep-0202/ https://spapas.github.io/2016/04/27/python-nested-list-comprehensions/