First of all, I think you're approach is ok. Oneliner, pretty pythonic.
The question suggested in the comments (Right-to-left string replace in Python?) provide several useful answers that worth measuring them.
One is the same approach you're taking: x[::-1].replace(' ', ' X ', 1)[::-1]
and the other one is with rsplit
and join
.
I profiled both and this was the output I got:
$python -mtimeit -s "s = 'foo bar bar'" "s[::-1].replace(' ', ' X ', 1)[::-1]"
1000000 loops, best of 3: 1.18 usec per loop
$python -mtimeit -s "s = 'foo bar bar'" "' X '.join(s.rsplit(' ',1))"
1000000 loops, best of 3: 0.8 usec per loop
So my recommendation is the second approach which seems a lot faster. That being said, whichever you chose, put a comment beside telling # this is right replacing!
because either way is pretty unclear what the code does :)
Hope this helps!