regex - How to insert a string between particular characters in Python? -
say have large parent string containing many characters. how can insert string between match of characters (and additionally, erase characters between matching characters)?
for example, largestring
guaranteed contain single set of ######
's (6 hash characters). how can insert smallstring
between it, ending similar (i guess better 'create string', since strings immutable):
largestring = "lorem ipsum ###### previous text erased ###### dolor sit amet" smallstring = "foo bar" newstring = "lorem ipsum ###### foo bar ###### dolor sit amet"
any ideas? assume use bit of regex...
something like
>>> import re >>> largestring = "lorem ipsum ###### previous text erased ###### dolor sit amet" >>> smallstring = "foo bar" >>> re.sub(r'(?<=###### ).*(?= ######)', smallstring, largestring) lorem ipsum ###### foo bar ###### dolor sit amet'
(?<=###### )
postive behind. asserts # prescedes string.*
matches anything(?= ######)
postive ahead. asserts # follows string
or
without arounds
>>> re.sub(r'(###### ).*( ######)', r'\1'+smallstring+r'\2', largestring) 'lorem ipsum ###### foo bar ###### dolor sit amet'
Comments
Post a Comment