如何使用“{0.word}”使用字符串格式

2024-09-29 00:15:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经阅读了Python标准库的第6节。以下是字符串格式:

"Weight in tons {0.weight}"      # 'weight' attribute of first positional arg

我不明白在.format括号中放置什么来用权重替换weight。如果有人能帮忙,我们将不胜感激。你知道吗

作为尝试,我尝试了以下方法,但失败了:

"Weight in tons {0.weight}".format({'weight':10})

错误:

AttributeError: 'dict' object has no attribute 'weight'

Tags: of字符串informat标准格式argattribute
2条回答

该语法用于属性,而不是键。如果要打印字典中的元素,请使用:

print("Weight in tons {0[weight]}".format({'weight':10}))

以下是.语法的有效用法:

class Dummy:
    def __init__(self):
        self.weight = 10

d = Dummy()
print("Weight in tons {0.weight}".format(d))

最后,不是这样:

"Weight in tons {0.weight}".format({'weight':10})

…您可能打算使用命名参数语法:

print("Weight in tons {weight}".format(weight=10))

像这样打开字典比较好

"Weight in tons {weight}".format(**{'weight':10})
# Weight in tons 10

因此,您可以简单地使用相应的键名访问这些值,如{weight}。你知道吗

相关问题 更多 >