简体   繁体   English

这是str.format上的Python 3错误吗?

[英]Is this a Python 3 bug on str.format?

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

does not result to 'INSERT INTO Product' but still 'INSERT INTO {}' why is this so? 不会导致“ INSERT INTO Product”,但仍然会导致“ INSERT INTO {}”,这是为什么呢?

Python 3.2 does this correctly: Python 3.2可以正确做到这一点:

$ 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. 如果格式字符串自行自行修改,这对于Python程序员来说将是非常烦人的,因为每个格式字符串只能使用一次。 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. 有时,我们希望有机会构建一个不错的格式字符串,然后使用数百次-如果format()返回结果而不是就地修改格式,这很容易。

format doesn't modify the string (it can't because strings are immutable). format不会修改字符串(因为字符串是不可变的,所以不能修改)。 It returns a new string. 它返回一个新字符串。 You need to assign the result of the call to format: 您需要将调用结果分配给format:

result = sqlstring.format(table)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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