Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to replace the end of a string, starting at a given substring

I have the string banana | 10 and want to replace everything from | to the end of the string with 9. The output I want would be banana | 9. How could I achieve this? I've looked into .replace(), .split() and converting the string into a list of characters, and looping over them until I find the bit that should be replaced, but just couldn't figure it out.

like image 584
Rea Mart Avatar asked Oct 22 '25 11:10

Rea Mart


1 Answers

I suggest you use re module(regex module):

import re
myString = "banana | 10"
re.sub(r"\|.+", r"| 9", myString)

Output

banana | 9
like image 102
TheFaultInOurStars Avatar answered Oct 25 '25 00:10

TheFaultInOurStars