How to Replace the Last Instance of a String in Python
- 1). Assign values to the string variables needed by this algorithm (the string where the substitution is to take place, the substring to be substituted, and the string which will substitute it) as in the following sample code:
corpus="9203320089237498743"
substituteThis="74"
substituteByThis=" nex " - 2). Find the last occurrence of the substring within the larger string, as in the following sample code:
remainder=corpus.rsplit(substituteThis,1)
The "rsplit" function performs right-to-left searches; therefore, the first occurrence it finds will be the last occurrence within the larger "corpus" string. - 3). Replace the smaller string within the larger one, as in the following sample code:
corpus=substituteByThis.join(remainder)
For the example, corpus will have value "9203320089237498 nex 3".
Source...