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

bkm*_*ron 68 python string arguments string-formatting

情况1:

"{arg1} {arg2}".format (10, 20)
Run Code Online (Sandbox Code Playgroud)

它会给出KeyError: 'arg1'因为我没有传递命名参数.

案例2:

"{arg1} {arg2}".format(arg1 = 10, arg2 = 20)
Run Code Online (Sandbox Code Playgroud)

现在它将正常工作,因为我传递了命名参数.它打印出来'10 20'

案例3:

并且,如果我传递错误的名字,它将显示 KeyError: 'arg1'

 "{arg1} {arg2}".format(wrong = 10, arg2 = 20)
Run Code Online (Sandbox Code Playgroud)

但,

案例4:

如果我以错误的顺序传递命名参数

"{arg1} {arg2}".format(arg2 = 10, arg1 = 20)
Run Code Online (Sandbox Code Playgroud)

有用...

它打印出来 '20 10'

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

Mar*_*ers 113

命名替换字段({...}在零件格式字符串匹配反对)的关键字参数.format()方法,而不是定位参数.

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

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

"{0} {1}".format(10, 20)
Run Code Online (Sandbox Code Playgroud)

在Python 2.7及更高版本中,您可以省略数字; {}然后,替换字段按格式化字符串中的外观顺序自动编号:

"{} {}".format(10, 20) 
Run Code Online (Sandbox Code Playgroud)

格式化字符串可以匹配位置关键字参数,并且可以多次使用参数:

"{1} {ham} {0} {foo} {1}".format(10, 20, foo='bar', ham='spam')
Run Code Online (Sandbox Code Playgroud)

引用格式字符串规范:

所述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)
Run Code Online (Sandbox Code Playgroud)

这里picture,link,descriptionprice是在所有按键row的字典,这是很容易看个究竟时,我运用row到格式化字符串.

  • 它不仅更具可读性,而且在处理自然语言和“国际化”(i18n) 时也非常有用,在这种情况下,您有时希望格式化消息的特定部分以不同的顺序以不同的语言出现。 (3认同)

Koe*_* G. 8

额外的好处包括

  • 不必担心参数的顺序。它们将落在字符串中的正确位置,如格式化程序中的名称所示。
  • 您可以将相同的参数放入字符串中两次,而不必重复该参数。例如"{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))
Run Code Online (Sandbox Code Playgroud)
I need foo (bar) and dead (beef)
I need test (case) and foo (bar) and then test again (case)
Run Code Online (Sandbox Code Playgroud)