How to insert string in each match using RegEx iterator

Peter Otten __peter__ at web.de
Wed Jun 10 02:24:57 EDT 2009


504crank at gmail.com wrote:

> By what method would a string be inserted at each instance of a RegEx
> match?
> 
> For example:
> 
> string = '123 abc 456 def 789 ghi'
> newstring = ' INSERT 123 abc INSERT 456 def INSERT 789 ghi'

Have a look at re.sub():

>>> s = '123 abc 456 def 789 ghi'
>>> re.compile(r"(\d+\s)").sub(r"INSERT \1", s)
'INSERT 123 abc INSERT 456 def INSERT 789 ghi'

Peter




More information about the Python-list mailing list