【发布时间】:2011-04-10 04:08:50
【问题描述】:
我想替换 Python 字符串末尾的字符。我有这个字符串:
s = "123123"
我想用x 替换最后一个2。假设有一个方法叫replace_last:
r = replace_last(s, '2', 'x')
print r
1231x3
有没有内置的或简单的方法可以做到这一点?
【问题讨论】:
我想替换 Python 字符串末尾的字符。我有这个字符串:
s = "123123"
我想用x 替换最后一个2。假设有一个方法叫replace_last:
r = replace_last(s, '2', 'x')
print r
1231x3
有没有内置的或简单的方法可以做到这一点?
【问题讨论】:
这正是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.
我写了这个函数来展示如何在你的用例中使用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
【讨论】:
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
【讨论】:
r = re.sub(r"2[^2]$", "x", s)
这是少数没有左右版本的字符串函数之一,但我们可以使用一些具有左右版本的字符串函数来模仿其行为。
>>> s = '123123'
>>> t = s.rsplit('2', 1)
>>> u = 'x'.join(t)
>>> u
'1231x3'
或
>>> 'x'.join('123123'.rsplit('2', 1))
'1231x3'
【讨论】:
rsplit()。当我去寻找解决这个问题的方法时,这对我来说是一个优势,因为否则我将不得不使用循环来进行多次替换。
>>> s = "aaa bbb aaa bbb"
>>> s[::-1].replace('bbb','xxx',1)[::-1]
'aaa bbb aaa xxx'
第二个例子
>>> s = "123123"
>>> s[::-1].replace('2','x',1)[::-1]
'1231x3'
【讨论】:
replace() normal sytax 进行正向和反向替换)。
当想要的匹配在字符串的末尾时,re.sub 来救援。
>>> import re
>>> s = "aaa bbb aaa bbb"
>>> s
'aaa bbb aaa bbb'
>>> re.sub('bbb$', 'xxx', s)
'aaa bbb aaa xxx'
>>>
【讨论】:
这是一个基于对您的问题的简单解释的解决方案。更好的答案需要更多信息。
>>> s = "aaa bbb aaa bbb"
>>> separator = " "
>>> parts = s.split(separator)
>>> separator.join(parts[:-1] + ["xxx"])
'aaa bbb aaa xxx'
更新
(在看到编辑后的问题后)另一个非常具体的答案。
>>> s = "123123"
>>> separator = "2"
>>> parts = s.split(separator)
>>> separator.join(parts[:-1]) + "x" + parts[-1]
'1231x3'
更新 2
有更好的way to do this。礼貌@mizipzor。
【讨论】:
txt = "123123"
txt = txt[::-1]
txt = txt.replace("2", "*", 1)
txt = txt[::-1]
【讨论】:
我得到了一个棘手的答案,但它的效率不够
>>> fname = '12345.png.pngasdfg.png'
>>> suffix = '.png'
>>> fname_rev = fname[::-1]
>>> suffix_rev = suffix[::-1]
>>> fullname_rev = fname_rev.replace(suffix_rev, '', 1)
>>> fullname = fullname_rev[::-1]
>>> fullname '12345.png.pngasdfg'
内置函数 replace() 接受三个参数
str.replace(old, new, max_time)
所以你可以从原始字符串中删除最后一个匹配的字符串
【讨论】:
对于第二个例子,我推荐rsplit,因为它使用起来非常简单,直接达到了目的。这是它的一个小功能:
def replace_ending(sentence, old, new):
if sentence.endswith(old):
i = sentence.rsplit(old,1)
new_sentence =new.join(i)
return new_sentence
return sentence
print(replace_ending("aaa bbb aaa bbb", "bbb", "xxx"))
输出:
aaa bbb aaa xxx
【讨论】:
有一种方法可以处理函数replace 以使其向后工作。
这个想法是从头到尾读取字符串、要替换的文本和新文本。逻辑保持不变。
这是基于使用[::-1] 向后切换字符串的方式。
例如:
>>> a = "123 456 123 456 123 456"
>>> print(a)
123 456 123 456 123 456
我们想用“abc”替换最后一个(或两个,或n)个“123”
>>> res = a[::-1].replace("123"[::-1], "abc"[::-1], 1)[::-1]
>>> print(res)
123 456 123 456 abc 456
这可以作为一个行为与替换完全相同的函数。
def replace_right(text, old, new, count=-1):
"""
Return a copy with all occurrences of substring old replaced by new starting from right.
"""
return text[::-1].replace(old[::-1], new[::-1], count)[::-1]
执行:
>>> replace_right(a, "123", "abc", 1)
'123 456 123 456 abc 456'
>>> replace_right(a, "123", "abc", 2)
'123 456 abc 456 abc 456'
【讨论】:
有一个非常简单的方法可以做到这一点,按照我的步骤操作
str = "stay am stay am delete am"
# want to remove the last am
str = str[:str.rfind('am')]
print(str)
首先,我们找到am最后一次出现的索引号,然后取第 0 个索引到该特定索引。
【讨论】:
str = "stay am stay am delete vvamvv gggg" # want to remove the last am str = str[:str.rfind('am')] + "REPLACED" + str[(str.rfind('am') + len("am")):] print(str)