gpt4 book ai didi

python - 是否有理由能够在 .format 中声明变量?

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

关于 .format()方法,请考虑以下示例:

print("{}, {} and {} are colors.".format("Red", "Blue", "Green"))

会输出

Red, Blue and Green are colors.

也可以使用索引(也许这不是正确的措辞):

print("{0}, {1} and {2} are colors.".format("Red", "Blue", "Green"))

那会输出同样的东西。

但是,他随后提出了一种声明变量的替代方法(同样,这可能不是正确的措辞),如下所示:

print("{r}, {b} and {g} are colors.".format(r="Red", b="Blue", g="Green"))

再次输出相同的结果。

使用像 r 这样的变量有什么好处吗? , bg.format()里面方法?

我想到的一件事是我可以稍后在程序中使用这些变量,但如果我尝试使用它们,我会得到一个 NameError: name 'r' is not defined .

最佳答案

Is there any advantage of using variables like r, b and g inside the .format() method?

当您需要多次引用同一个对象时,使用关键字参数特别有用。

演示:

>>> class Signal: 
...: status = 'on'
...: color = 'red'
...:
>>> 'the signal is {sig.status} and the color is {sig.color}'.format(sig=Signal)
the signal is on and the color is red

你也可以达到同样的效果

>>> 'the signal is {0.status} on the color is {0.color}'.format(Signal)                                         
the signal is on on the color is red

但是使用名称可以让阅读代码的人更容易理解字符串。

此外,关键字参数可以按任何顺序传递,而您必须确保以正确的顺序传递位置参数。这是另一个示例,它有望展示关键字参数的可用性优势。

>>> class Fighter: 
...: def __init__(self, name, attack, defense):
...: self.name = name
...: self.attack = attack
...: self.defense = defense
>>>
>>> Bob = Fighter('Bob', 100, 80)
>>> Tom = Fighter('Tom', 80, 90)
>>> template = 'Attacker {attacker.name} attempts hit at {defender.name} with {attacker.attack} (ATK) against {defender.defense} (DEF)'
>>>
>>> template.format(attacker=Bob, defender=Tom)
'Attacker Bob attempts hit at Tom with 100 (ATK) against 90 (DEF)'
>>> template.format(defender=Tom, attacker=Bob)
'Attacker Bob attempts hit at Tom with 100 (ATK) against 90 (DEF)'

关于python - 是否有理由能够在 .format 中声明变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53980427/

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