[ACCEPTED]-Python re.sub question-regex

Accepted answer
Score: 32

You can specify a callback when using re.sub, which 6 has access to the groups: http://docs.python.org/library/re.html#text-munging

a = 'foo'
b = 'bar'

text = 'find a replacement for me [[:a:]] and [[:b:]]'

desired_output = 'find a replacement for me foo and bar'

def repl(m):
    contents = m.group(1)
    if contents == 'a':
        return a
    if contents == 'b':
        return b

print re.sub('\[\[:(.+?):\]\]', repl, text)

Also notice the 5 extra ? in the regular expression. You want 4 non-greedy matching here.

I understand this 3 is just sample code to illustrate a concept, but 2 for the example you gave, simple string 1 formatting is better.

Score: 8

Sounds like overkill. Why not just do something 1 like

text = "find a replacement for me %(a)s and %(b)s"%dict(a='foo', b='bar')

?

Score: 2
>>> d={}                                                
>>> d['a'] = 'foo'                                      
>>> d['b'] = 'bar' 
>>> text = 'find a replacement for me [[:a:]] and [[:b:]]'
>>> t=text.split(":]]")
>>> for n,item in enumerate(t):
...   if "[[:" in item:
...      t[n]=item[: item.rindex("[[:") +3 ] + d[ item.split("[[:")[-1]]
...
>>> print ':]]'.join( t )
'find a replacement for me [[:foo:]] and [[:bar:]]'

0

More Related questions