Python 中的格式化字符串和命名参数 [英] format strings and named arguments in Python

查看:26
本文介绍了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.

推荐答案

命名替换字段(格式字符串) 匹配关键字参数.format() 方法,而不是位置参数.

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

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

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

这里,picturelinkdescriptionprice都是row 字典,当我将 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.

这篇关于Python 中的格式化字符串和命名参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆