2

How to string.replace once starting from the right?

I could do it from the left.

>>> x = 'foo bar bar'
>>> x.replace(' ', ' X ', 1)
'foo X bar bar'

Or with re.sub:

>>> import re
>>> re.sub(' ', ' X ', x, 1)
'foo X bar bar'

From the right, i could do:

>>> x = 'foo bar bar'
>>> x[::-1].replace(' ', ' X ', 1)[::-1]
'foo bar X bar'

But is there any other way to replace once starting from the right?

Charles
  • 50,943
  • 13
  • 104
  • 142
alvas
  • 115,346
  • 109
  • 446
  • 738

1 Answers1

1

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!

Community
  • 1
  • 1
Paulo Bu
  • 29,294
  • 6
  • 74
  • 73