views:

34

answers:

2

I have the idea to use a regex pattern as a template and wonder if there is a convenient way to do so in Python (3 or newer).

import re

pattern = re.compile("/something/(?P<id>.*)")
pattern.populate(id=1) # that is what I'm looking for

should result in

/something/1
+2  A: 

that's not what regex are for, you could just use normal string formatting.

>>> '/something/{id}'.format(id=1)
'/something/1'
SilentGhost
Why the down vote? This answer looks correct to me
Peter Gibson
+1  A: 

Save the compile until after the substitution:

pattern = re.compile("/something/(?P<%s>.*)" % 1)
Bryan Oakley