Finding last occurrence of substring in string, replacing that
Solution 1:
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:]
Solution 2:
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. -'
Solution 3:
I would use a regex:
import re
new_list = [re.sub(r"\.(?=[^.]*$)", r". - ", s) for s in old_list]
Solution 4:
A one liner would be :
str=str[::-1].replace(".",".-",1)[::-1]
Solution 5:
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]