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

时间:2010-09-09 09:24:27

标签: python string replace

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

 s = "123123"

我想将2替换为x。假设有一个名为replace_last的方法:

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

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

10 个答案:

答案 0 :(得分:31)

这正是rpartition函数用于:

  

rpartition(...)       S.rpartition(sep) - > (头,sep,尾巴)

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

答案 1 :(得分:24)

使用正则表达式函数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

答案 2 :(得分:7)

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

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

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

答案 3 :(得分:6)

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

答案 4 :(得分:2)

这是一个基于对您的问题的简单解释的解决方案。更好的答案需要更多信息。

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

答案 5 :(得分:2)

当想要的匹配位于字符串末尾时,re.sub即可解决。

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

答案 6 :(得分:0)

我得到了一个棘手的答案,但是效率不够


    >>> 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) 因此,您可以从原始字符串中删除最后一个保留的字符串

答案 7 :(得分:0)

对于第二个示例,我建议使用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

答案 8 :(得分:0)

有一种方法可以处理函数 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'

答案 9 :(得分:0)

有一个非常简单的方法来做到这一点,按照我的步骤

str = "stay am stay am  delete am"
#  want to remove the last am
str = str[:str.rfind('am')]
print(str)

首先,我们找到 am 最后一次出现的索引号,然后将第 0 个索引取到该特定索引。

相关问题