简体   繁体   中英

Variable Substitution in Python

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('mail@mail.mail', "tomail@tomail.tomail", 'Subject', 'Hello $name')

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

@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 . Eg,

print( f'Hello {name}' )

Python does not in general do PHP-style variable interpolation.

What you are seeing in the first statement is a special feature of db.select which picks the variable values out of the local variables in the context of the caller.

If you want to substitute in the variable in your second line, you will have to do it manually with one of the ways Python provides. Here is one such way.

web.sendmail('mail@mail.mail', "tomail@tomail.tomail", 'Subject', 'Hello %s' % name)

Here is another way.

web.sendmail('mail@mail.mail', "tomail@tomail.tomail", 'Subject', 'Hello {0}'.format(name))

The first option is documented in String Formatting operations .

See the documentation for str.format and Format String Syntax for more details on the second option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM