How to remove or replace substring in Python determined by start and end point?

python, regex, string

Solution

I guess you want something like that, without regex:

def replace_between(text, begin, end, alternative=''):
    middle = text.split(begin, 1)[1].split(end, 1)[0]
    return text.replace(middle, alternative)

Not tested and you should protected the first line from exception (if begin or end is not found), but the idea is here :)

Problem

From time to time I would remove or replace substring of one long string. Therefore, I would determine one start patern and one end patern which would determine start and end point of substring: ``` long_string = "lorem ipsum..white chevy..blah,blah...lot of text..beer bottle....and so to the end" removed_substr_start = "white chevy" removed_substr_end = "beer bott" # this is pseudo method down STRresult = long_string.replace( [from]removed_substr_start [to]removed_substr_end, "") ```

Original source