Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python's ".format" function

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.

like image 777
duke_nukem Avatar asked Apr 15 '12 07:04

duke_nukem


People also ask

What is the format function in Python?

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.

What does the format function return in Python?

The format() function returns a formatted representation of a given value specified by the format specifier.

How many formats are there in format () function are?

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.

What is .2f in Python?

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.


1 Answers

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)
like image 88
okm Avatar answered Oct 01 '22 20:10

okm