在Python中格式化字符串和命名参数

2024-03-28 22:28:30 发布

您现在位置:Python中文网/ 问答频道 /正文

案例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'

我的问题是为什么它有效,在这种情况下,命名参数的用法是什么。


Tags: format用法参数顺序错误情况名字命名
2条回答

额外的好处包括

  • 您不必担心参数的顺序。它们将落在字符串的正确位置,如格式化程序中的名称所示。
  • 您可以将同一个参数放在字符串中两次,而不必重复该参数。E、 g."{foo} {foo}".format(foo="bar")给出“bar bar”

请注意,您也可以提供额外的参数而不会导致错误。 当

  • 稍后更改字符串格式化程序的次数较少,因此出错的可能性也较小。如果它不包含新的命名参数,format函数仍将工作,而不更改参数,并将参数放在格式化程序中指示它们的位置。
  • 可以让多个格式化程序字符串共享一组参数。例如,在这种情况下,您可以有一个包含所有参数的字典,然后根据需要在格式化程序中选择它们。

例如:

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

命名替换字段(aformat string中的{...}部分)与.format()方法的关键字参数匹配,而不是与位置参数匹配。

关键字参数就像字典中的键;顺序无关紧要,因为它们与名称匹配。

如果要与位置参数匹配,请使用数字:

"{0} {1}".format(10, 20)

在Python2.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)

这里,picturelinkdescriptionprice都是row字典中的键,而且当我将row应用于格式化字符串时,更容易看到发生了什么。

相关问题 更多 >