Finding last occurrence of substring in string, replacing that

PythonStringParsing

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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 - Python

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 - Python

I would use a regex:

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

Solution 4 - Python

A one liner would be :

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

Solution 5 - Python

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]

Solution 6 - Python

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.

Solution 7 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdam MagyarView Question on Stackoverflow
Solution 1 - PythonAditya SihagView Answer on Stackoverflow
Solution 2 - PythonVarinder SinghView Answer on Stackoverflow
Solution 3 - PythonTim PietzckerView Answer on Stackoverflow
Solution 4 - PythonmazsView Answer on Stackoverflow
Solution 5 - PythonbambusteView Answer on Stackoverflow
Solution 6 - PythonArpan SainiView Answer on Stackoverflow
Solution 7 - PythonAlex LView Answer on Stackoverflow