Variable Substitution in Python

yrk picture yrk · Jun 27, 2014 · Viewed 23.6k times · Source

So I'm working with Web.py and I have following code:

check = db.select('querycode', where='id=$id', vars=locals())[0]

Which works fine, it substitutes $id with the variable. But in this line it does not work:

web.sendmail('[email protected]', "[email protected]", 'Subject', 'Hello $name')

What do I wrong and how could it work. Also did I get the concept right: A $-sign substitutes the variable?

Answer

shx2 picture shx2 · Jun 27, 2014

@merlin2011's answer explains it best.

But just to complement it, since you're trying to substitute by variable name, python also supports the following form of "substitution" (or string formatting):

'Hello %(name)s' % locals()

Or to limit the namespace:

'Hello %(name)s' % {'name': name}

EDIT Since python 3.6, variable substitution is a done natively using f-strings. E.g.,

print( f'Hello {name}' )