I want to replace characters at the end of a python string. I have this string:
s = "123123"
I want to replace the last 2
with x
. Suppose there is a method called replace_last
:
r = replace_last(s, '2', 'x') print r 1231x3
Is there any built-in or easy method to do this?
Try following code: str = str. replaceAll("\\/$", "");
Using 'str.replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.
Use the String. replace() method to replace the last character in a string, e.g. const replaced = str.
This is exactly what the rpartition
function is used for:
rpartition(...) S.rpartition(sep) -> (head, sep, tail)
Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S.
I wrote this function showing how to use rpartition
in your use case:
def replace_last(source_string, replace_what, replace_with): head, _sep, tail = source_string.rpartition(replace_what) return head + replace_with + tail s = "123123" r = replace_last(s, '2', 'x') print r
Output:
1231x3
re.sub
to replace words at end of stringimport re s = "123123" s = re.sub('23$', 'penguins', s) print s
Prints:
1231penguins
or
import re s = "123123" s = re.sub('^12', 'penguins', s) print s
Prints:
penguins3123
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