小编Dav*_*ave的帖子

为什么.format()不能与声明分开使用?

有人可以向我解释.format()方法发生了什么,它只能处理字符串声明,而不能处理包含字符串的变量吗?

下面是工作和失败代码的示例,后面跟着每个代码的输出

# This works fine
s = "{0} \n" \
    "{1} \n" \
    "{2}\n" \
    .format("Hello", "world", "from a multiline string")
print(s)

# This does not
f = "{0} \n" \
    "{1} \n" \
    "{2}\n"

f.format("Hello", "world", "from a multiline string")
print(f)
Run Code Online (Sandbox Code Playgroud)

各自的产出

Hello 
world 
from a multiline string

{0} 
{1} 
{2}
Run Code Online (Sandbox Code Playgroud)

我试过这个,在braces({})中没有数字,也没有通过赋值({aname})和传递关键字参数.我想了解格式方法如何处理它们的第一个和第二个例子之间的区别,以及是否有一种方法来格式化包含与实际声明分开的字符串的变量.

python string format python-3.x

0
推荐指数
2
解决办法
63
查看次数

标签 统计

format ×1

python ×1

python-3.x ×1

string ×1