duk*_*kem 5 python string formatting dictionary
最近,我发现''.format函数非常有用,因为与%格式化相比,它可以提高可读性.试图实现简单的字符串格式化:
data = {'year':2012, 'month':'april', 'location': 'q2dm1'}
year = 2012
month = 'april'
location = 'q2dm1'
a = "year: {year}, month: {month}, location: {location}"
print a.format(data)
print a.format(year=year, month=month, location=location)
print a.format(year, month, location)
Run Code Online (Sandbox Code Playgroud)
虽然两个第一次打印的格式符合我的预期(是的,something=something看起来很难看,但这只是一个例子),最后一个会提高KeyError: 'year'.在python中有没有创建字典的技巧,所以它会自动填充键和值,例如somefunc(year, month, location)输出{'year':year, 'month': month, 'location': location}?
我是python的新手,无法找到关于这个主题的任何信息,但是像这样的技巧会大大改善和缩小我当前的代码.
提前谢谢并原谅我的英语.
第一个print应该是
print a.format(**data)
Run Code Online (Sandbox Code Playgroud)
此外,如果你找到一些快捷方式,你可以写一个像,没有大的区别.
def trans(year, month, location):
return dict(year=year, month=month, location=location)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19521 次 |
| 最近记录: |