How to replace the some characters from the end of

2019-03-14 10:25发布

问题:

I want to replace characters at the end of a python string. I have this 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?

回答1:

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


回答2:

Using regular expression function re.sub to replace words at end of string

import re
s = "123123"
s = re.sub('23$', 'penguins', s)
print s

Prints:

1231penguins

or

import re
s = "123123"
s = re.sub('^12', 'penguins', s)
print s

Prints:

penguins3123


回答3:

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'


回答4:

>>> 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'


回答5:

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'
>>> 


回答6:

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.