Finding last occurrence of substring in string, replacing that

Adam Magyar picture Adam Magyar · Jan 24, 2013 · Viewed 135.4k times · Source

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.

Answer

Aditya Sihag picture Aditya Sihag · Jan 24, 2013

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