在Python中格式化字符串和命名参数 [英] format strings and named arguments in Python
问题描述
案例1:
"{arg1} {arg2}".format (10, 20)
它将给出KeyError: 'arg1'
,因为我没有传递命名参数.
It will give KeyError: 'arg1'
because I didn't pass the named arguments.
案例2:
"{arg1} {arg2}".format(arg1 = 10, arg2 = 20)
现在它可以正常工作,因为我传递了命名参数.
并打印'10 20'
Now it will work properly because I passed the named arguments.
And it prints '10 20'
案例3:
而且,如果我输入了错误的名称,它将显示KeyError: 'arg1'
And, If I pass wrong name it will show KeyError: 'arg1'
"{arg1} {arg2}".format(wrong = 10, arg2 = 20)
但是
案例4:
如果我以错误的顺序
"{arg1} {arg2}".format(arg2 = 10, arg1 = 20)
它可以工作...
并显示'20 10'
我的问题是为什么它起作用,在这种情况下,命名参数的用途是什么.
My question is why it works and what's the use of named arguments in this case.
推荐答案
命名替换字段(.format()
方法匹配,而不与位置参数匹配.
Named replacement fields (the {...}
parts in a format string) match against keyword arguments to the .format()
method, and not positional arguments.
关键字参数类似于字典中的关键字;顺序无关紧要,因为它们与名称匹配.
Keyword arguments are like keys in a dictionary; order doesn't matter, as they are matched against a name.
如果要与 positional 参数匹配,请使用数字:
If you wanted to match against positional arguments, use numbers:
"{0} {1}".format(10, 20)
在Python 2.7及更高版本中,您可以省略数字.然后,{}
替换字段将按照出现在格式字符串中的顺序自动编号:
In Python 2.7 and up, you can omit the numbers; the {}
replacement fields are then auto-numbered in order of appearance in the formatting string:
"{} {}".format(10, 20)
格式字符串可以与位置和关键字参数匹配,并且可以多次使用参数:
The formatting string can match against both positional and keyword arguments, and can use arguments multiple times:
"{1} {ham} {0} {foo} {1}".format(10, 20, foo='bar', ham='spam')
引用格式字符串规范:
字段名称本身以 arg_name 开头,该 arg_name 是数字或关键字.如果是数字,则表示位置参数;如果是关键字,则表示命名关键字参数.
The field_name itself begins with an arg_name that is either a number or a keyword. If it’s a number, it refers to a positional argument, and if it’s a keyword, it refers to a named keyword argument.
强调我的.
如果要创建一个较大的格式化字符串,则使用命名替换字段通常更易读和可维护,因此您不必继续计算参数并弄清楚什么参数会出现在结果字符串中.
If you are creating a large formatting string, it is often much more readable and maintainable to use named replacement fields, so you don't have to keep counting out the arguments and figure out what argument goes where into the resulting string.
您还可以使用**keywords
调用语法将现有字典应用于某种格式,从而轻松地将CSV文件转换为格式化输出:
You can also use the **keywords
calling syntax to apply an existing dictionary to a format, making it easy to turn a CSV file into formatted output:
import csv
fields = ('category', 'code', 'price', 'description', 'link', 'picture', 'plans')
table_row = '''\
<tr>
<td><img src="{picture}"></td>
<td><a href="{link}">{description}</a> ({price:.2f})</td>
</tr>
'''
with open(filename, 'rb') as infile:
reader = csv.DictReader(infile, fieldnames=fields, delimiter='\t')
for row in reader:
row['price'] = float(row['price']) # needed to make `.2f` formatting work
print table_row.format(**row)
在这里,picture
,link
,description
和price
都是row
词典中的键,并且更容易看看我应用row
转换为格式字符串.
Here, picture
, link
, description
and price
are all keys in the row
dictionary, and it is much easier to see what happens when I apply the row
to the formatting string.
这篇关于在Python中格式化字符串和命名参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!