本文介绍了python的“.format”功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我发现''。格式函数非常有用,因为它可以提高可读性与格式化。
尝试实现简单的字符串格式:

Recently, I found ''.format function very useful because it can improve readability a lot comparing to the % formatting.Trying to achieve simple string formatting:

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':year,'month':month,'location':location}

Whilst two first prints do format as I expect (yes, something=something looks ugly, but that's an example only), the last one would raise KeyError: 'year'.Is there any trick in python to create dictionary so it will automatically fill keys and values, for example somefunc(year, month, location) will output {'year':year, 'month': month, 'location': location}?

我很新到python,找不到任何关于这个话题的信息,但是这样的技巧会大大改善和缩小我目前的代码。

I'm pretty new to python and couldn't find any info on this topic, however a trick like this would improve and shrink my current code drastically.

提前感谢,赦免我的英文。

Thanks in advance and pardon my English.

推荐答案

第一个打印应该是

print a.format(**data)

另外,如果你找到一些捷径,你可以写一个没有什么大的区别。

Also, if you are finding some shortcuts, you could write one like, no big difference.

def trans(year, month, location):
    return dict(year=year, month=month, location=location)

这篇关于python的“.format”功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 16:40