ArrowsX
ArrowsX

Reputation: 535

Using .format() with tuples instead of dictionaries

I have this line in my code that uses dictionary:

print("{} {}".format(holiday["data"].strftime("%d/%m"), holiday["description"]))

I don't know if it is more elegant, but I want to make this example to be applied as a tuple.

Upvotes: 0

Views: 100

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1121804

If the two values are in a tuple, you can use the fact that datetime and date objects support formatting with str.format() directly:

holiday_tuple = (datetime.date(2015, 3, 1), 'some description')
print("{:%d/%m} {}".format(*holiday_tuple))

The *arg syntax applies the two elements in holiday_tuple as separate arguments.

You can also have the string template do the extraction:

print("{0[0]:%d/%m} {0[1]}".format(holiday_tuple))

Demo:

>>> import datetime
>>> holiday_tuple = (datetime.date(2015, 3, 1), 'some description')
>>> print("{:%d/%m} {}".format(*holiday_tuple))
01/03 some description
>>> print("{0[0]:%d/%m} {0[1]}".format(holiday_tuple))
01/03 some description

I'd have done something similar with the dictionary; rather than extract the keys from the dictionary in the arguments, have these extracted either by using **kwargs syntax or with using the indexing syntax:

holiday_dictionary = {'data': datetime.date(2015, 3, 1), 'description': 'some description')
print("{data:%d/%m} {description}".format(**holiday_dictionary))
print("{0[data]:%d/%m} {0[description]}".format(holiday_dictionary))

Upvotes: 1

Jon Clements
Jon Clements

Reputation: 142136

No need to worry about tuples here, if indeed you do have a dict, then you can use str.format to do it directly from the dict, eg:

from datetime import datetime

holiday = {
    'data': datetime.today(),
    'description': 'Would love one'
}

res = '{data:%d/%m} {description}'.format(**holiday)
# 01/03 Would love one

Upvotes: 0

Malik Brahimi
Malik Brahimi

Reputation: 16711

Try use integers indices, depending on which index corresponds to which value. If your holiday variable is a tuple, that is. Otherwise, you should create a dictionary and use your original line of code.

print("{} {}".format(holiday[0].strftime("%d/%m"), holiday[1]))

Upvotes: 0

Related Questions