Reputation:
I want to make a regex of that search for the final occurence of given alphabet in a string.
import re
string = "Hello stackoverflow"
[print(re.sub('o', '*', string))]
i'm expecting "Hello stackoverfl*w" as the result
Upvotes: 1
Views: 53
Reputation: 521457
We can try using re.sub
for a regex option:
string = "Hello stackoverflow"
output = re.sub(r'^(.*)o(.*)$', '\\1*\\2', string)
print(output)
This prints:
Hello stackoverfl*w
Upvotes: 1
Reputation: 169344
You could reverse the string, do the replacement once, and return the re-reversed string:
re.sub('o','*',string[::-1],1)[::-1]
# ^ this means do the replacement only once
Upvotes: 1