views:

69

answers:

2

hi,

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

+7  A: 

Make use of the power of regular expressions. 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).

AndiDog
thank you. to extend this i found out i can define a function before the re.sub and apply it to the replace argument without calling it and passing the matchobject.
aschmid00
+1  A: 

It's also pretty easy to do it without regex in your case:

s = "my 'cat' is 'white'".split("'")
# the parts between the ' are at the 1, 3, 5 .. index 
print s[1::2]
# replace them with new elements
s[1::2] = [x+x for x in s[1::2]]
# join that stuff back together
print "'".join(s)
THC4k
this is not a really good solution. "'white' is my 'cat'" for example....
aschmid00
@aschmid00: That gives "'whitewhite' is my 'catcat'" ... as expected, or not?
THC4k
yes ur right but still not a pretty solution in my point of view.
aschmid00