Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding last occurrence of substring in string, replacing that

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.

like image 782
Adam Magyar Avatar asked Jan 24 '13 07:01

Adam Magyar


People also ask

How do you find the last occurrence of a substring in a string?

The rfind() method finds the last occurrence of the specified value. The rfind() method returns -1 if the value is not found. The rfind() method is almost the same as the rindex() method.

How do you replace a substring in a string?

Algorithm to Replace a substring in a stringInput the full string (s1). Input the substring from the full string (s2). Input the string to be replaced with the substring (s3). Find the substring from the full string and replace the new substring with the old substring (Find s2 from s1 and replace s1 by s3).

How do I change the last occurrence of a string in Python?

Using replace() function. In Python, the string class provides a function replace(), and it helps to replace all the occurrences of a substring with another substring. We can use that to replace only the last occurrence of a substring in a string.


2 Answers

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:] 
like image 176
Aditya Sihag Avatar answered Oct 02 '22 18:10

Aditya Sihag


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. -' 
like image 20
Varinder Singh Avatar answered Oct 02 '22 18:10

Varinder Singh