Callum
Callum

Reputation: 1165

Python Insert Variables into String

So i'm not great at regular expressions but i'd like to insert variables into a string. My string will look something like this (just a random example):

(%foo% * 3) / 2

And I would need to insert variables into it, %foo% being the name of the variable I need to use and might end up looking like this:

(4 * 3) / 2

I know I could do this using string formatting but each string may require different variables. Is there a good way that I can just create a regular expression that will swap out the placeholders with the variables?

Upvotes: 1

Views: 361

Answers (1)

alecxe
alecxe

Reputation: 473833

You can still use string formatting with named arguments:

>>> "{foo}, {bar}".format(foo=2, bar=4)
'2, 4'

Upvotes: 2

Related Questions