python 命名关键字参数_在Python中格式化字符串和命名参数

Case 1:

"{arg1} {arg2}".format (10, 20)

It will give KeyError: 'arg1' because I didn't pass the named arguments.

Case 2:

"{arg1} {arg2}".format(arg1 = 10, arg2 = 20)

Now it will work properly because I passed the named arguments.

And it prints '10 20'

Case 3:

And, If I pass wrong name it will show KeyError: 'arg1'

"{arg1} {arg2}".format(wrong = 10, arg2 = 20)

But,

Case 4:

If I pass the named arguments in wrong order

"{arg1} {arg2}".format(arg2 = 10, arg1 = 20)

It works...

and it prints '20 10'

My question is why it works and what's the use of named arguments in this case.

解决方案

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)

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

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.

Emphasis mine.

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.

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 = '''\

{description} ({price:.2f})

'''

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)

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值