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.
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.
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).
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.
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:]
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. -'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With