繁体   English   中英

查找字符串中最后一次出现的子字符串,替换它

[英]Finding last occurrence of substring in string, replacing that

所以我有一长串相同格式的字符串,我想找到最后一个“。” 每个字符中的字符,并用“。 - ”替换它。 我尝试过使用rfind,但我似乎无法正确使用它来做到这一点。

这应该做到这一点

old_string = "this is going to have a full stop. some written sstuff!"
k = old_string.rfind(".")
new_string = old_string[:k] + ". - " + old_string[k+1:]

要从右边取代:

def replace_right(source, target, replacement, replacements=None):
    return replacement.join(source.rsplit(target, replacements))

正在使用:

>>> replace_right("asd.asd.asd.", ".", ". -", 1)
'asd.asd.asd. -'

我会使用正则表达式:

import re
new_list = [re.sub(r"\.(?=[^.]*$)", r". - ", s) for s in old_list]

一个班轮将是:

str=str[::-1].replace(".",".-",1)[::-1]

您可以使用下面的函数替换右侧第一次出现的单词。

def replace_from_right(text: str, original_text: str, new_text: str) -> str:
    """ Replace first occurrence of original_text by new_text. """
    return text[::-1].replace(original_text[::-1], new_text[::-1], 1)[::-1]
a = "A long string with a . in the middle ending with ."

#如果你想找到任何字符串最后一次出现的索引,在我们的例子中,#will会找到最后一次出现的索引

index = a.rfind("with") 

#结果将是44,因为索引从0开始。

天真的做法:

a = "A long string with a . in the middle ending with ."
fchar = '.'
rchar = '. -'
a[::-1].replace(fchar, rchar[::-1], 1)[::-1]

Out[2]: 'A long string with a . in the middle ending with . -'

Aditya Sihag用一个​​单一的rfind回答:

pos = a.rfind('.')
a[:pos] + '. -' + a[pos+1:]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM