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 does it work and what's the use of named arguments in this case.


解决方案

命名替换字段({...} 部分.org/2/library/string.html#format-string-syntax" rel="noreferrer">格式字符串) 匹配 keyword arguments 到 .format() 方法,而不是位置参数.

Named replacement fields (the {...} parts in a format string) match against keyword arguments to the .format() method, and not positional arguments.

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

Keyword arguments are like keys in a dictionary; order doesn't matter, as they are matched against a name.

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

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

引用格式字符串规范:

field_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='	')
    for row in reader:
        row['price'] = float(row['price'])  # needed to make `.2f` formatting work
        print table_row.format(**row)

这里,picturelinkdescriptionprice都是row<中的key/code> 字典,并且当我将 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.

相关文章