Replace all text between two lines of python

Let's say I have:

a = r''' Example This is a very annoying string that takes up multiple lines and h@s a// kind{s} of stupid symbols in it ok String''' 

I need a way to make a replacement (or just delete) and the text between "This" and "ok" so that when I call it, now it’s equal:

 a = "Example String" 

I cannot find any wildcards that seem to work. Any help is greatly appreciated.

+8
source share
5 answers

You need Regular Expression :

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

The DOTALL flag is the key. Usually "." a character does not match newlines, so you cannot match strings in a string. If you set the DOTALL flag, re will match ". *" For as many lines as needed.

+3
source
 a=re.sub('This.*ok','',a,flags=re.DOTALL) 
0
source

If you need the first and last words:

 re.sub(r'^\s*(\w+).*?(\w+)$', r'\1 \2', a, flags=re.DOTALL) 
0
source

Another method is to use line splitting:

 def replaceTextBetween(delimeterA, delimterB, contents, innerContent): contentsPrefix = contents.split(delimeterA)[0] contentsSuffix = contents.split(delimterB)[1] return contentsPrefix + delimeterA + innerContent + delimterB + contentsSuffix 

Limitations:

  • Does not check if delimiters exist
  • No duplicate separators assumed
0
source

All Articles