案例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'
我的问题是,为什么它会工作,在本例中,命名参数的用途是什么。
发布于 2013-07-27 08:30:50
命名替换字段( {...}部件在格式字符串中)与.format()方法的关键字参数匹配,而不是位置参数。
关键字参数就像字典中的键;顺序并不重要,因为它们与名称匹配。
如果要与位置参数匹配,请使用数字:
"{0} {1}".format(10, 20)在Python2.7和更高版本中,您可以省略数字;然后,{}替换字段按照格式字符串中的外观顺序自动编号:
"{} {}".format(10, 20) 格式化字符串可以匹配位置参数和关键字参数,并且可以多次使用参数:
"{1} {ham} {0} {foo} {1}".format(10, 20, foo='bar', ham='spam')引用格式字符串规范的话
field_name本身以一个arg_name开头,它要么是,要么是数字,要么是关键字。如果它是一个数字,它引用一个位置参数,如果它是一个关键字,它引用一个命名的关键字参数。
强调我的。
如果您要创建一个大型格式化字符串,那么使用命名替换字段通常更容易阅读和维护,因此您不必一直计算参数,并弄清楚结果字符串中的参数是什么。
您还可以使用**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应用于格式化字符串时,更容易看到发生了什么。
发布于 2019-09-12 08:02:46
额外的好处包括
"{foo} {foo}".format(foo="bar")给出了“酒吧”请注意,您也可以提供额外的参数而不会导致错误。所有这些都特别有用
例如:
>d = {"foo":"bar", "test":"case", "dead":"beef"}
>print("I need foo ({foo}) and dead ({dead})".format(**d))
>print("I need test ({test}) and foo ({foo}) and then test again ({test})".format(**d))I need foo (bar) and dead (beef)
I need test (case) and foo (bar) and then test again (case)https://stackoverflow.com/questions/17895835
复制相似问题