Last updated: Apr 9, 2024
Reading timeยท5 min
To replace the last occurrence of a substring in a string:
str.rsplit()
method to split the string on the substring, once,
from the right.str.join()
method to join the list with the replacement string as
the separator.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.
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.
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:
Name | Description |
---|---|
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.
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.
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.
This is a two-step process:
str.rfind()
method to get the index of the last occurrence of the
substring.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.
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.
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.
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'))
To replace the Nth occurrence of a substring in a string:
def replace_nth(string, old, new, n): index_of_occurrence = string.find(old) occurrence = int(index_of_occurrence != -1) print(occurrence) # ๐๏ธ find index of Nth occurrence while index_of_occurrence != -1 and occurrence != n: index_of_occurrence = string.find(old, index_of_occurrence + 1) occurrence += 1 # ๐๏ธ index of Nth occurrence found, replace substring if occurrence == n: return ( string[:index_of_occurrence] + new + string[index_of_occurrence+len(old):] ) # ๐๏ธ if N occurrences of substring not found in string, return string return string my_str = 'one one one two' new_str = replace_nth(my_str, 'one', '_', 1) print(new_str) # ๐๏ธ _ one one two new_str = replace_nth(my_str, 'one', '_', 2) print(new_str) # ๐๏ธ one _ one two new_str = replace_nth(my_str, 'one', '_', 3) print(new_str) # ๐๏ธ one one _ two new_str = replace_nth(my_str, 'one', '_', 100) print(new_str) # ๐๏ธ one one one two new_str = replace_nth(my_str, 'abc', '_', 100) print(new_str) # ๐๏ธ one one one two
We used the str.find()
method to find the index of the first occurrence of the
substring in the string.
The str.find
method returns the index of the first occurrence of the provided
substring in the string.
-1
if the substring is not found in the string.If the str.find()
method doesn't return -1
, then the substring is contained
at least once in the string.
The str.rfind()
method can be passed a start
index argument to start looking
for a substring after the specified index.
The purpose of the while
loop is to iterate until it finds the Nth occurrence
of the substring in the string.
while index_of_occurrence != -1 and occurrence != n: index_of_occurrence = string.find(old, index_of_occurrence + 1) occurrence += 1
str.find()
method returns -1
and the occurrences
variable is not set to n
, then the substring is not contained N times in the string.If the occurrence
variable gets set to n
, then we have found the index of
the Nth occurrence of the substring in the string.
if occurrence == n: return ( string[:index_of_occurrence] + new + string[index_of_occurrence+len(old):] )
In this case, we use string slicing to replace the substring.
The slice string[:index_of_occurrence]
starts at index 0 and goes up to, but
not including the index of the Nth occurrence of the substring.
We used the addition (+) operator to append the replacement string.
The slice string[index_of_occurrence+len(old):]
starts at the index after the
last character of the Nth occurrence of the substring that is to be replaced.
If the substring is not contained in the string N times, we return the string as is.
You can learn more about the related topics by checking out the following tutorials: