gpt4 book ai didi

python - str.format() 选项不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 12:28:05 26 4
gpt4 key购买 nike

此代码摘自教程:

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!

关于python - str.format() 选项不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20396161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com