re.sub and variables

Steven D'Aprano steve at
Fri Aug 13 04:03:48 CEST 2010

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.


More information about the Python-list mailing list