programmatically find and replace content dynamically in a string in python
Question: i need to find and replace patterns in a string with a dynamically generated
content.

lets say i want to find all strings within '' in the string and double the
string. a string like:

`my 'cat' is 'white'` should become my `'catcat' is 'whitewhite'`

all matches could also appear twice in the string.

thank you


Answer: Make use of the power of [regular
expressions](http://docs.python.org/library/re.html). In this particular case:

    
    
    import re
    
    s = "my 'cat' is 'white'"
    
    print re.sub("'([^']+)'", r"'\1\1'", s) # prints my 'catcat' is 'whitewhite'
    

`\1` refers to the first group in the regex (called `$1` in some other
implementations).

