案例 1:
"{arg1} {arg2}".format(10, 20)
它会给出 KeyError: 'arg1'
因为我没有传递命名参数。
案例 2:
"{arg1} {arg2}".format(arg1=10, arg2=20)
现在它可以正常工作了,因为我传递了命名参数。
它打印出 '10 20'
案例 3:
而且,如果我传递了错误的名称,它会显示 KeyError: 'arg1'
"{arg1} {arg2}".format(wrong=10, arg2=20)
但是,
案例 4:
如果我以错误的顺序
传递命名参数"{arg1} {arg2}".format(arg2=10, arg1=20)
它有效...
它会打印出 '20 10'
我的问题是它为什么会起作用以及在这种情况下命名参数有什么用。
最佳答案
命名替换字段(format string 中的 {...}
部分)与 关键字参数 匹配到 .format()
方法,而不是位置参数。
关键字参数就像字典中的键;顺序无关紧要,因为它们与 name 匹配。
如果您想匹配 位置 参数,请使用数字:
"{0} {1}".format(10, 20)
在 Python 2.7 及更高版本中,您可以省略数字; {}
然后替换字段会按照在格式化字符串中出现的顺序自动编号:
"{} {}".format(10, 20)
格式化字符串可以匹配位置和关键字参数,并且可以多次使用参数:
"{1} {ham} {0} {foo} {1}".format(10, 20, foo='bar', ham='spam')
引自 format string specification :
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.
强调我的。
如果您正在创建一个大格式字符串,使用命名替换字段通常更易读和维护,因此您不必一直计算参数并找出结果字符串中的哪个参数。
您也可以使用 **keywords
调用语法以将现有字典应用于格式,从而轻松将 CSV 文件转换为格式化输出:
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
时会发生什么到格式化字符串。
关于python - Python中的格式化字符串和命名参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17895835/