Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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('[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?

like image 205
yrk Avatar asked Jun 27 '14 08:06

yrk


People also ask

How do you substitute a variable in Python?

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.

What is substitution in Python?

Python String | replace() The replace() in Python returns a copy of the string where all occurrences of a substring are replaced with another substring.

What is a variable in substitution?

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.

What are the 4 variables in Python?

Python variables are of four different types: Integer, Long Integer, Float, and String.


2 Answers

@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}' )
like image 169
shx2 Avatar answered Oct 13 '22 11:10

shx2


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.

like image 33
merlin2011 Avatar answered Oct 13 '22 10:10

merlin2011