Replace last occurrence of character in string python

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

  1. Solve "ValueError invalid literal for int() with base 10" - Python
  2. Handling dynamic subdomain with Flask - Python
  3. A minimal example about WordPress object cache
  4. Select random element from a list - Python
  5. 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:

  1. Use the str.rsplit() method to split the string on the substring, once, from the right.
  2. 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 three

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

NameDescription
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 three

The 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.com

Alternatively, 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:

  1. Use the str.rfind() method to get the index of the last occurrence of the substring.
  2. 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!

print('abc abc 123'.rfind('abc')) # ๐Ÿ‘‰๏ธ 4

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.

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

Call str. rfind(char) to get the index of the last occurrence of char in str . Use the syntax str[:index] + "c" + str[index+1:] to replace the character located at index with "c" in str . last_char_index = original_string.

How do you replace the last occurrence of a character in a string?

To replace the last occurrence of a character in a string: Use the lastIndexOf() method to get the last index of the character. Call the substring() method twice, to get the parts of the string before and after the character to be replaced. Add the replacement character between the two calls to the substring method.

How do I remove the last occurrence of a character from a string in Python?

rstrip. The string method rstrip removes the characters from the right side of the string that is given to it. So, we can use it to remove the last element of the string. We don't have to write more than a line of code to remove the last char from the string.

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

To replace the last N characters in a string using indexing, select all characters of string except the last n characters i.e. str[:-n]. Then add replacement substring after these selected characters and assign it back to the original variable.