是否有理由能够在.​​format内部声明变量?

时间:2018-12-30 18:46:32

标签: python

我正在在线关注某个Python教程,并且该老师正在讲授.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

3 个答案:

答案 0 :(得分:7)

  

在.format()方法中使用rbg之类的变量是否有优势?

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

演示:

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

答案 1 :(得分:1)

0、1、2等仅充当打印的占位符。例如:

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

打印

Red, Blue and Green are colors.

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

打印

Blue, Red and Green are colors.

另一方面,

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

只需按照提供给format的参数顺序打印。

但是,当您这样做时,

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

您只是在创建或重新定义占位符,从012a,{{1} }和b,其范围是c / format命令的本地

答案 2 :(得分:0)

有时名称更容易理解,有时您希望从更多的选项中挑选出 some 个字典元素。

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

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

请注意,当使用名称时,字符串模板比何时提供更多的信息 您使用自动编号或显式编号的字段,一眼就能看到将要插入的信息种类。