Python 如何替换字符串末尾的某些字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3675318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:11:33  来源:igfitidea点击:

How to replace the some characters from the end of a string?

pythonstringreplace

提问by Freewind

I want to replace characters at the end of a python string. I have this string:

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

 s = "123123"

I want to replace the last 2with x. Suppose there is a method called replace_last:

我想2x. 假设有一个方法叫做replace_last

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

Is there any built-in or easy method to do this?

是否有任何内置或简单的方法可以做到这一点?

采纳答案by Mizipzor

This is exactly what the rpartitionfunction is used for:

这正是该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(...) 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 rpartitionin your use case:

我写了这个函数,展示了如何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

Output:

输出:

1231x3

回答by Manoj Govindan

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

更新 2

There is far better way to do this. Courtesy @mizipzor.

有更好的方法来做到这一点。礼貌@mizipzor

回答by Sepheus

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

回答by gimel

When the wanted match is at the end of string, re.subcomes to the rescue.

当想要的匹配在字符串的末尾时,re.sub就派上用场了。

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

回答by Tony Ingraldi

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

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

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

回答by Chris Adams

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'

回答by Yiling Liu

I got a tricky answer, but it is not efficient enough

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


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

Built-in function replace() takes three arguments str.replace(old, new, max_time)So you can delete the last mached string from the origional string

内置函数 replace() 接受三个参数 str.replace(old, new, max_time)所以你可以从原始字符串中删除最后一个被加工的字符串

回答by ghazouani Ahmed

For the second example, I would recommend rsplit, as it is very simple to use and and directly achieves the goal. Here is a little function with it:

对于第二个示例,我会推荐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")) 

Output:

输出:

aaa bbb aaa xxx

aaa bbb aaa xxx