简体   繁体   English

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

[英]Is there a reason to be able to declare a variable inside .format?

I'm following a certain Python tutorial online and the tutor is teaching about the .format() method. 我正在网上关注某个Python教程,导师正在教授.format()方法。

For example: 例如:

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

will output 将输出

Red, Blue and Green are colors.

It's also possible to use indexing (maybe this is not the right wording): 也可以使用索引(也许这不是正确的措辞):

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

that would output the same thing. 这将输出相同的东西。

However, he then proposed an alternative of declaring variables (again, probably this is not the right wording) like the following: 然而,他然后提出了另一种声明变量的方法(再次,可能这不是正确的措辞),如下所示:

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

That again outputs the same result. 这再次输出相同的结果。

Is there any advantage of using variables like r , b and g inside the .format() method? .format()方法中使用rbg等变量是否有任何优势?

One thing I thought about it is that I could use these variables later on in the program but if I try to use them I get a NameError: name 'r' is not defined . 我想到的一件事是我可以在程序中使用这些变量,但如果我尝试使用它们,我会得到一个NameError: name 'r' is not defined

Is there any advantage of using variables like r , b and g inside the .format() method? 在.format()方法中使用rbg等变量是否有任何优势?

Using keyword arguments is especially useful when you need to refer to the same object more than once. 当您需要多次引用同一个对象时,使用关键字参数尤其有用。

Demo: 演示:

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

You could have achieved the same with 你可以实现同样的目标

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

but using names makes the string easier to interpret for humans that read the code. 但是使用名称可以使字符串更容易解释为读取代码的人。

In addition, keyword arguments can be passed in any order, while you would have to make sure to pass positional arguments in the correct order. 此外,关键字参数可以按任何顺序传递,而您必须确保以正确的顺序传递位置参数。 Here's another example which hopefully demonstrates the usability advantages of keyword-arguments. 这是另一个希望证明关键字参数的可用性优势的例子。

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

0, 1, 2 etc. simply acts as the placeholders for printing. 0,1,2等只是作为打印占位符。 For ex: 例如:

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

prints 版画

Red, Blue and Green are colors.

whereas

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

prints 版画

Blue, Red and Green are colors.

On the other hand, 另一方面,

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

would simply print in the order of arguments provided to format . 只是按照format提供的参数顺序打印。

However, when you do, 但是,当你这样做时,

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

you are simply kind of creating or redefining the place holders from 0 , 1 and 2 to a , b and c whose scope is local to the format / print command 你只是创建或从重新定义占位012abc其范围是本地的format / print命令

Sometimes names are just easier to comprehend, and sometimes you want to pick out some of the elements of a dictionary with more options. 有时名字更容易理解,有时候你想要选择一些字典的元素来提供更多选项。

Say you have a configurable set of strings that provide information on your system, where you put information on a wide variety of subjects in a dictionary. 假设您有一组可配置的字符串,这些字符串提供有关系统的信息,您可以在字典中将各种主题的信息放在其中。 Like a flight system: 像飞行系统一样:

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',
    ...
}

you can use {name} fields (with or without formatting) in your configurable strings: 您可以在可配置字符串中使用{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.
'''

and you can re-use the same dictionary for any of those messages: 并且您可以为任何这些消息重复使用相同的字典:

print(short_status.format(**information))
print(captains_message.format(**information))

Note how having used names, the string templates are a lot more informative then when you use auto-numbered or explicitly numbered fields, you can see, at a glance, immediately what kind of information is going to be slotted there. 注意如何使用名称,字符串模板提供更多信息,然后当您使用自动编号或显式编号字段时,您可以一目了然地看到将在那里插入什么样的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM