Holy fuck.
I randomly encountered this behavior while testing something entirely unrelated, and googled around until I found some evidence that this was a known issue:
Quoth Matz, the creator of Ruby:
> "string ".gsub(/\s*$/, 'P')
> "stringPP"
The first try replaces all trailing spaces with "P", then second try
replaces empty at the end of string with "P".
Well, wait a second here -- after the first replacement, you'll have zero characters left to consume, right? Then after the second replacement, you still have zero characters left to consume. So shouldn't /\s*$/ match again? And again?
Apparently, I'm not the first person to have their mind blown by this, and apparently (reading to the end of the comments), Python sometimes gets it right and sometimes gets it wrong, making this one of the rare cases where Python gets anything wrong.