Python 在字符串中查找最后一次出现的子字符串,替换它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14496006/
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
Finding last occurrence of substring in string, replacing that
提问by Adam Magyar
So I have a long list of strings in the same format, and I want to find the last "." character in each one, and replace it with ". - ". I've tried using rfind, but I can't seem to utilize it properly to do this.
所以我有一长串相同格式的字符串,我想找到最后一个“。” 每个字符中的字符,并将其替换为“. - ”。我试过使用 rfind,但我似乎无法正确利用它来做到这一点。
采纳答案by Aditya Sihag
This should do it
这应该做
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:]
回答by Tim Pietzcker
I would use a regex:
我会使用正则表达式:
import re
new_list = [re.sub(r"\.(?=[^.]*$)", r". - ", s) for s in old_list]
回答by Alex L
Na?ve approach:
天真的方法:
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's answer with a single rfind:
Aditya Sihag 的回答是rfind:
pos = a.rfind('.')
a[:pos] + '. -' + a[pos+1:]
回答by Varinder Singh
To replace from the right:
从右侧替换:
def replace_right(source, target, replacement, replacements=None):
return replacement.join(source.rsplit(target, replacements))
In use:
正在使用:
>>> replace_right("asd.asd.asd.", ".", ". -", 1)
'asd.asd.asd. -'
回答by mazs
A one liner would be :
一个班轮将是:
str=str[::-1].replace(".",".-",1)[::-1]
str=str[::-1].replace(".",".-",1)[::-1]
回答by Arpan Saini
a = "A long string with a . in the middle ending with ."
# if you want to find the index of the last occurrence of any string, In our case we #will find the index of the last occurrence of with
# 如果你想找到任何字符串最后一次出现的索引,在我们的例子中,我们#will找到最后一次出现的索引 with
index = a.rfind("with")
# the result will be 44, as index starts from 0.
# 结果将是 44,因为索引从 0 开始。
回答by bambuste
You can use the function below which replaces the first occurrence of the word from right.
您可以使用下面的函数来替换右边第一个出现的单词。
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]

