str.format()选项不起作用

时间:2013-12-05 09:30:04

标签: python string format

此代码取自教程:

def main():
    stri = "Hello, {person}"
    stri.format(person="James")
    print(stri) #prints "Hello, {person}"

为什么format()无效?

1 个答案:

答案 0 :(得分:10)

确实有效。您只是没有将格式分配给变量,然后只打印原始字符串。见下面的例子:

>>> 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!