如何在Python中使用.format方法提取特定格式的数据

时间:2019-02-20 17:43:24

标签: python

我有一个元组:

exam_st_date = (11, 12, 2014)

我必须以以下格式提取日期:

The examination will start from : 11 / 12 / 2014

我必须使用.format方法来完成此任务。

在以下情况下有效:

>>> exam_st_date = (11, 12, 2014)
>>> print("The examination will start from : {} / {} / {} ".format(exam_st_date[0], exam_st_date[1], exam_st_date[2]))
The examination will start from : 11 / 12 / 2014 

但是,如果出现以下情况,为什么它不起作用

>>> exam_st_date = (11, 12, 2014)
>>> print("The examination will start from : {} / {} / {} ".format(exam_st_date()))
Traceback (most recent call last):
..., line 7, in <module>
    print("The examination will start from : {} / {} / {} ".format(exam_st_date()))
TypeError: 'tuple' object is not callable

请说明解决此任务的最佳方法。

1 个答案:

答案 0 :(得分:0)

您能做的最好的是

print("The examination will start from : {} / {} / {} ".format(*exam_st_date)) # unpacking the tuple

使用我将推荐的datetime模块

from datetime import datetime
dt = datetime(*exam_st_date[::-1])
print("The examination will start from : {} / {} / {} ".format(dt.day,dt.month,dt.year))