Search code examples
pythonstringsubstring

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.


Solution

  • I suggest you use re module(regex module):

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

    Output

    banana | 9