Replace all text between 2 strings python

Another method is to use string splits:

def replaceTextBetween(originalText, delimeterA, delimterB, replacementText):
    leadingText = originalText.split(delimeterA)[0]
    trailingText = originalText.split(delimterB)[1]

    return leadingText + delimeterA + replacementText + delimterB + trailingText

Limitations:

  • Does not check if the delimiters exist
  • Assumes that there are no duplicate delimiters
  • Assumes that delimiters are in correct order

You need Regular Expression:

>>> import re
>>> re.sub('\nThis.*?ok','',a, flags=re.DOTALL)
' Example String'

The DOTALL flag is the key. Ordinarily, the '.' character doesn't match newlines, so you don't match across lines in a string. If you set the DOTALL flag, re will match '.*' across as many lines as it needs to.

Tags:

Python