Skip to main content
 首页 » 编程设计

python之如何使用字符串格式使用 "{0.word}"

2025年05月04日30lautakyan007

我一直在阅读 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' 

请您参考如下方法:

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

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