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,description且price是在所有按键row的字典,这是很容易看个究竟时,我运用row到格式化字符串.
额外的好处包括
"{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)
| 归档时间: |
|
| 查看次数: |
57404 次 |
| 最近记录: |