views:

66

answers:

6

My question is very simple, but I didn't get the answer from google.

There is a python string:

 s = "123123"

I want to replace the last 2 with x. Suppose there is a method called replace_last:

 r = replace_last(s, '2', 'x')
 print r
 1231x3

Is there any built-in or easy method to do this?


UPDATE

Sorry, guys, since someone said my example is not clear, I just edited my example, but not quickly enough.

What I want is just replace a string with another string once, its similar with python's:

string.replace('a', 'b', 1)

But is from the end to beginning.

+1  A: 

Here is a solution based on a simplistic interpretation of your question. A better answer will require more information.

>>> s = "aaa bbb aaa bbb"
>>> separator = " "
>>> parts = s.split(separator)
>>> separator.join(parts[:-1] + ["xxx"])
'aaa bbb aaa xxx'

Update

(After seeing edited question) another very specific answer.

>>> s = "123123"
>>> separator = "2"
>>> parts = s.split(separator)
>>> separator.join(parts[:-1]) + "x" + parts[-1]
'1231x3'

Update 2

There is far better way to do this. Courtesy @mizipzor.

Manoj Govindan
Very sorry, I just edited my question, make it clearer.
Freewind
@Manoj, thank you all the same :)
Freewind
+1  A: 
>>> s = "aaa bbb aaa bbb"
>>> s[::-1].replace('bbb','xxx',1)[::-1]
'aaa bbb aaa xxx'

For your second example

>>> s = "123123"
>>> s[::-1].replace('2','x',1)[::-1]
'1231x3'
Sepheus
A: 

When the wanted match is at the end of string, re.sub comes to the rescue.

>>> import re
>>> s = "aaa bbb aaa bbb"
>>> s
'aaa bbb aaa bbb'
>>> re.sub('bbb$', 'xxx', s)
'aaa bbb aaa xxx'
>>> 
gimel
A: 

Using regular expressions, this is straight-forward

import re

s = "123123"

re.sub('23$', 'x3', s)

Tony Ingraldi
+5  A: 

This is exactly what the rpartition function is used for:

rpartition(...) S.rpartition(sep) -> (head, sep, tail)

Search for the separator sep in S, starting at the end of S, and return
the part before it, the separator itself, and the part after it.  If the
separator is not found, return two empty strings and S.

I wrote this function showing how to use rpartition in your use case:

def replace_last(source_string, replace_what, replace_with):
    head, sep, tail = source_string.rpartition(replace_what)
    return head + replace_with + tail

s = "123123"
r = replace_last(s, '2', 'x')
print r

Output:

1231x3
mizipzor
+1. I stand enlightened.
Manoj Govindan
@mizipzor, thank you! You know best what I want!
Freewind
A: 

This is one of the few string functions that doesn't have a left and right version, but we can mimic the behaviour using some of the string functions that do.

>>> s = '123123'
>>> t = s.rsplit('2', 1)
>>> u = 'x'.join(t)
>>> u
'1231x3'

or

>>> 'x'.join('123123'.rsplit('2', 1))
'1231x3'
ChrisAdams