【发布时间】:2012-04-26 23:19:57
【问题描述】:
最近,我发现''.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)
虽然前两个打印的格式符合我的预期(是的,something=something 看起来很丑,但这只是一个示例),最后一个会引发KeyError: 'year'。
python中是否有任何技巧来创建字典,以便它会自动填充键和值,例如somefunc(year, month, location)将输出{'year':year, 'month': month, 'location': location}?
我对 python 很陌生,找不到关于这个主题的任何信息,但是这样的技巧会大大改善和缩小我当前的代码。
先谢谢了,请原谅我的英语。
【问题讨论】:
标签: python string dictionary formatting