Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是否有理由在.format中声明变量?_Python - Fatal编程技术网

Python 是否有理由在.format中声明变量?

Python 是否有理由在.format中声明变量?,python,Python,我正在关注某个Python在线教程,该教程正在教授.format()方法 例如: print("{}, {} and {} are colors.".format("Red", "Blue", "Green")) 将输出 Red, Blue and Green are colors. 也可以使用索引(可能这不是正确的措辞): 这将输出相同的东西 然而,他随后提出了声明变量的替代方案(同样,这可能不是正确的措辞),

我正在关注某个Python在线教程,该教程正在教授
.format()
方法

例如:

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

Red, Blue and Green are colors.
也可以使用索引(可能这不是正确的措辞):

这将输出相同的东西

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

print("{r}, {b} and {g} are colors.".format(r="Red", b="Blue", g="Green"))
这同样会输出相同的结果

.format()
方法中使用
r
b
g
等变量有什么好处吗?


我考虑过的一件事是,我可以在以后的程序中使用这些变量,但如果我尝试使用它们,我会得到一个
名称错误:名称“r”未定义

0、1、2等。只是用作打印的占位符。例如:

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

Red, Blue and Green are colors.
Blue, Red and Green are colors.
鉴于

印刷品

Red, Blue and Green are colors.
Blue, Red and Green are colors.
另一方面,

print("{}, {} and {} are colors.".format("Red", "Blue", "Green"))
只需按照提供给
格式的参数顺序打印即可

然而,当你这样做的时候

print("{r}, {b} and {g} are colors.".format(r="Red", b="Blue", g="Green"))
您只需创建或重新定义占位符,从
0
1
2
a
b
c
,其范围是
格式
/
打印
命令的本地范围

在.format()方法中使用
r
b
g
等变量有什么好处吗

当需要多次引用同一对象时,使用关键字参数尤其有用

演示:

你也可以用它来达到同样的效果

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

有时名字更容易理解,有时你想用更多的选项来挑选字典中的一些元素

假设您有一组可配置的字符串,这些字符串提供有关系统的信息,您可以将各种主题的信息放入词典中。就像一个飞行系统:

information = {
    'speed': 10
    'altitude': 2500
    'time': datetime.datetime(2018, 12, 30, 18, 53, 44)
    'heading': 249,
    'eta': datetime.datetime(2018, 12, 30, 22, 30, 00)
    'flightnumber': 'MPA4242',
    'destination': 'LGW',
    'destination_name': 'London Gatwick Airpoirt',
    ...
}
您可以在可配置字符串中使用
{name}
字段(带格式或不带格式):

short_status = 'Current status: flying at {speed} mph at {altitude} feet, heading {heading} degrees, ETA {eta:%H:%M}'
captains_message = '''
    Hi, this is your Captain speaking. We are currently flying at {altitude} feet,
    at a speed of {speed} mph, making good time to arrive at {destination_name} in
    good time for our scheduled {eta:%H:%M}' landing.
'''
您可以对这些消息中的任何一条重复使用相同的词典:

print(short_status.format(**information))
print(captains_message.format(**information))
请注意,使用名称后,字符串模板的信息量比使用
如果使用自动编号或显式编号的字段,您可以一眼就看到将在其中插入何种信息。

这些是关键字参数,而不是新变量。
print(short_status.format(**information))
print(captains_message.format(**information))