如何从字符串末尾替换一些字符?

Fre*_*ind 25 python string replace

我想替换python字符串末尾的字符.我有这个字符串:

 s = "123123"
Run Code Online (Sandbox Code Playgroud)

我想,以取代过去2x.假设有一个方法叫做replace_last:

 r = replace_last(s, '2', 'x')
 print r
 1231x3
Run Code Online (Sandbox Code Playgroud)

有没有内置或简单的方法来做到这一点?

Miz*_*zor 35

这正是rpartition函数用于:

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.
Run Code Online (Sandbox Code Playgroud)

我写了这个函数,展示了如何rpartition在你的用例中使用:

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
Run Code Online (Sandbox Code Playgroud)

输出:

1231x3
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案是有缺陷的。如果未找到replace_what 字符串,则将replace_with 插入到该字符串的开头。 (2认同)

小智 24

使用正则表达式函数re.sub替换字符串末尾的单词

import re
s = "123123"
s = re.sub('23$', 'penguins', s)
print s
Run Code Online (Sandbox Code Playgroud)

打印:

1231penguins
Run Code Online (Sandbox Code Playgroud)

要么

import re
s = "123123"
s = re.sub('^12', 'penguins', s)
print s
Run Code Online (Sandbox Code Playgroud)

打印:

penguins3123
Run Code Online (Sandbox Code Playgroud)


Chr*_*ams 8

这是少数几个没有左右版本的字符串函数之一,但我们可以使用一些字符串函数来模仿行为.

>>> s = '123123'
>>> t = s.rsplit('2', 1)
>>> u = 'x'.join(t)
>>> u
'1231x3'
Run Code Online (Sandbox Code Playgroud)

要么

>>> 'x'.join('123123'.rsplit('2', 1))
'1231x3'
Run Code Online (Sandbox Code Playgroud)

  • +1:除了比公认的解决方案更短的时候,这个解决方案的优势在于,只需改变`rsplit()`中第二个参数的值,就可以根据需要从右边做出尽可能多的替换.当我寻找这个问题的解决方案时,这对我来说是一个优势,因为否则我将不得不使用循环来进行多次替换. (3认同)

Sep*_*eus 6

>>> s = "aaa bbb aaa bbb"
>>> s[::-1].replace('bbb','xxx',1)[::-1]
'aaa bbb aaa xxx'
Run Code Online (Sandbox Code Playgroud)

第二个例子

>>> s = "123123"
>>> s[::-1].replace('2','x',1)[::-1]
'1231x3'
Run Code Online (Sandbox Code Playgroud)

  • 这只适用于回文,修复: source[::-1].replace(old[::-1], new[::-1], count)[::-1] (2认同)

gim*_*mel 6

当想要的匹配位于字符串末尾时,re.sub就会出现。

>>> import re
>>> s = "aaa bbb aaa bbb"
>>> s
'aaa bbb aaa bbb'
>>> re.sub('bbb$', 'xxx', s)
'aaa bbb aaa xxx'
>>> 
Run Code Online (Sandbox Code Playgroud)