old_string = "MK-36-W-357-IJO-36-MDR" k = old_string.rfind("-") new_string = old_string[:k] + "." + old_string[k+1:] print(new_string) #Result will be MK-36-W-357-IJO-36.MDR
Recent Posts
- Solve "ValueError invalid literal for int() with base 10" - Python
- Handling dynamic subdomain with Flask - Python
- A minimal example about WordPress object cache
- Select random element from a list - Python
- Write our first Selenium program with Python 3 & Firefox
This article was published on September 15, 2016
Your Questions / Comments
If you found this article interesting, found errors, or just want to discuss about it, please get in touch.
Replace last occurrence of Substring in String in Python #
To replace the last occurrence of a substring in a string:
- Use the str.rsplit() method to split the string on the substring, once, from the right.
- Use the str.join() method to join the list with the replacement string as the separator.
Copied!
my_str = 'one two two' def replace_last(string, old, new): return new.join(string.rsplit(old, 1)) # 👇️ one two three print(replace_last(my_str, 'two', 'three')) new_str = 'three'.join(my_str.rsplit('two', 1)) print(new_str) # 👉️ one two threeThe first step is to use the str.rsplit() method to split the string into a list, once, from the right.
Copied!
my_str = 'one two two' # 👇️ ['one two ', ''] print(my_str.rsplit('two', 1))The str.rsplit method returns a list of the words in the string using the provided separator as the delimiter string.
Copied!
my_str = 'bobby hadz com' print(my_str.rsplit(' ')) # 👉️ ['bobby', 'hadz', 'com'] print(my_str.rsplit(' ', 1)) # 👉️ ['bobby hadz', 'com']The method takes the following 2 arguments:
separator | Split the string into substrings on each occurrence of the separator |
maxsplit | At most maxsplit splits are done, the rightmost ones (optional) |
Except for splitting from the right, rsplit() behaves like split().
The last step is to use the str.join() method to join the list into a string with the replacement as the separator.
Copied!
my_str = 'one two two' new_str = 'three'.join(my_str.rsplit('two', 1)) print(new_str) # 👉️ one two threeThe str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.
The string the method is called on is used as the separator between the elements.
If the substring is not found in the string, the string is returned as is.
Copied!
my_str = 'bobbyhadz.com' new_str = 'three'.join(my_str.rsplit('two', 1)) print(new_str) # 👉️ bobbyhadz.comAlternatively, you can use the str.rfind() method.
Replace last occurrence of Substring in String using rfind() #
To replace the last occurrence of a substring in a string:
- Use the str.rfind() method to get the index of the last occurrence of the substring.
- Use string slicing to replace the last occurrence of the substring in the string.
Copied!
def replace_last(string, old, new): if old not in string: return string index = string.rfind(old) return string[:index] + new + string[index+len(old):] # 👇️ one two three print(replace_last('one two two', 'two', 'three')) # 👇️ 'abc _ 123' print(replace_last('abc abc 123', 'abc', '_'))We first check if the substring is not found in the string, in which case we return the string as is.
We used the str.rfind() method to get the index of the last occurrence of the substring in the string.
The str.rfind method returns the highest index in the string where the provided substring is found.
Copied!
The method returns -1 if the substring is not contained in the string.
The slice string[:index] starts at index 0 and goes up to, but not including the index of the last occurrence of the substring.
Copied!
def replace_last(string, old, new): if old not in string: return string index = string.rfind(old) return string[:index] + new + string[index+len(old):] # 👇️ one two three print(replace_last('one two two', 'two', 'three')) # 👇️ 'abc _ 123' print(replace_last('abc abc 123', 'abc', '_'))We then use the addition (+) operator to append the replacement string.
The slice string[index+len(old):] starts at the index after the last character of the substring to be replaced.
If the substring is not contained in the string, we return the string as is.
Copied!
def replace_last(string, old, new): if old not in string: return string index = string.rfind(old) return string[:index] + new + string[index+len(old) - 1:] # 👇️ bobbyhadz.com print(replace_last('bobbyhadz.com', 'two', 'three'))Which approach you pick is a matter of personal preference. I'd go with using the str.rsplit() and str.join() methods for readability purposes.