如何替换字符串末尾的字符?

50 投票
11 回答
98522 浏览
提问于 2025-04-16 03:54

我想要替换一个Python字符串末尾的字符。我有这个字符串:

s = "123123"

我想把最后的 2 替换成 x。假设有一个叫 replace_last 的方法:

>>> replace_last(s, '2', 'x')
'1231x3'

有没有什么内置的或者简单的方法可以做到这一点呢?


这和Python的 str.replace() 有点像:

>>> s.replace('2', 'x', 1)
'1x3123'

不过是从后往前替换的。

11 个回答

17

这是少数几个没有左右版本的字符串函数之一,不过我们可以用一些其他有左右版本的字符串函数来模拟它的行为。

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

或者

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

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

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

输出:

1231penguins

或者

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

输出:

penguins3123
46

这正是 rpartition 函数的用途:

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

这个函数会在字符串 S 中查找分隔符 sep,从字符串的末尾开始查找,然后返回分隔符前面的部分、分隔符本身,以及分隔符后面的部分。如果没有找到分隔符,就返回两个空字符串和原来的字符串 S

我写了这个函数,展示了如何在你的场景中使用 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

输出结果:

1231x3

撰写回答