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)
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}
?
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.
Format Function in Python (str. format()) is technique of the string category permits you to try and do variable substitutions and data formatting. It enables you to concatenate parts of a string at desired intervals through point data format.
The format() function returns a formatted representation of a given value specified by the format specifier.
In Python Programming, we use format functions to format our data. There are two types of format functions in Python, one is the format() function which is used to convert a value to a formatted representation and the other is the str.
As expected, the floating point number (1.9876) was rounded up to two decimal places – 1.99. So %. 2f means to round up to two decimal places. You can play around with the code to see what happens as you change the number in the formatter.
The first print
should be
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With