此代码取自教程:
def main(): stri = "Hello, {person}" stri.format(person="James") print(stri) #prints "Hello, {person}"
为什么format()
不工作?
它确实有效.您只是没有将格式分配给变量,然后只打印原始字符串.见下面的例子:
>>> s = 'hello, {person}' >>> s 'hello, {person}' >>> s.format(person='james') 'hello, james' # your format works >>> print s # but you did not assign it hello, {person} # original `s` >>> x = s.format(person='james') # now assign it >>> print x hello, james # works!