查找字符串中子字符串的最后一个匹配项,替换

因此,我有一个相同格式的字符串的长列表,我想找到最后一个“字符,并将其替换为”。- ".我试过使用 rfind,但似乎不能正确地使用它来完成这项工作。

142499 次浏览

I would use a regex:

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

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

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:

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

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

A one liner would be :

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

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

index = a.rfind("with")

# the result will be 44, as index starts from 0.

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]