re.sub and variables

MRAB python at mrabarnett.plus.com
Thu Aug 12 22:20:30 EDT 2010


Steven D'Aprano wrote:
> On Thu, 12 Aug 2010 14:33:28 -0700, fuglyducky wrote:
> 
>> if anyone happens to know about
>> passing a variable into a regex that would be great.
> 
> The same way you pass anything into any string.
> 
> Regexes are ordinary strings. If you want to construct a string from a 
> variable t = "orl", you can do any of these:
> 
> "Hello w" + t + "d"
> 
> "".join(["Hello", " ", "w", t, "d"])
> 
> "Hello w%sd" % t
> 
> "Hello %s" % ("w" + t + "d")
> 
> "Hello w%(var)sd" % {"var": t}
> 
> "Hello wSPAMd".replace("SPAM", t)
> 
> or many other variations. Constructing a regex is no different.
> 
You just need to remember that if you pass a string into re.sub as a
replacement then it'll be treated as a template. It's all in the
documentation! :-)



More information about the Python-list mailing list