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?
subs() method, we can substitute all instances of a variable or expression in a mathematical expression with some other variable or expression or value. Parameters: variable – It is the variable or expression which will be substituted. substitute – It is the variable or expression or value which comes as substitute.
Python String | replace() The replace() in Python returns a copy of the string where all occurrences of a substring are replaced with another substring.
Variable substitutions are a flexible way to adjust configuration based on your variables and the context of your deployment. You can often tame the number and complexity of your variables by breaking them down into simple variables and combining them together using expressions.
Python variables are of four different types: Integer, Long Integer, Float, and String.
@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}' )
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('[email protected]', "[email protected]", 'Subject', 'Hello %s' % name)
Here is another way.
web.sendmail('[email protected]', "[email protected]", '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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With