How to substitute into a regular expression group in Python

Posted by peter on Stack Overflow See other posts from Stack Overflow or by peter
Published on 2010-06-17T05:41:25Z Indexed on 2010/06/17 6:23 UTC
Read the original article Hit count: 304

Filed under:
|
>>> s = 'foo: "apples", bar: "oranges"'
>>> pattern = 'foo: "(.*)"'

I want to be able to substitute into the group like this:

>>> re.sub(pattern, 'pears', s, group=1)
'foo: "pears", bar: "oranges"'

Is there a nice way to do this?

© Stack Overflow or respective owner

Related posts about python

Related posts about regex