Question

sqlstring = 'INSERT INTO {}'
table = 'Product'
sqlstring.format(table)

does not result to 'INSERT INTO Product' but still 'INSERT INTO {}' why is this so?

Was it helpful?

Solution

Python 3.2 does this correctly:

$ python3.2
Python 3.2.2 (default, Sep  5 2011, 22:09:30) 
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> sqlstring = 'INSERT INTO {}'
>>> table = 'Product'
>>> sqlstring.format(table)
'INSERT INTO Product'
>>> 

What version are you using?

Additional thought:

Strings are immutable and do not self-modify in-place. Maybe you want:

sqlstring = sqlstring.format(table)

If format strings self-modified themselves in place it would be quite annoying for Python programmers, as each format string could only be used once. Sometimes we want the chance to build a nice format string then use it hundreds of times — which is easy if format() returns the result instead of modifying the format in-place.

OTHER TIPS

format doesn't modify the string (it can't because strings are immutable). It returns a new string. You need to assign the result of the call to format:

result = sqlstring.format(table)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top