使用字典将月号转换为月名的基本Python编程

使用字典将月号转换为月名的基本Python编程,python,python-2.7,Python,Python 2.7,我是python新手,只知道最基本的级别。 我应该允许以dd/mm/yyyy的形式输入日期,并将其转换为类似1986年8月26日的格式。 我被困在如何将我的月份(mm)从数字转换为文字。 下面是我目前的代码,希望你能帮助我。 **请不要建议使用日历功能,我们应该使用dict来解决这个问题 谢谢你(: 拆分日期字符串时,只有三个元素(0、1和2): 因此,日期[:2]将等于: >>> day=date[:2] # that is, date up to (but not incl

我是python新手,只知道最基本的级别。 我应该允许以dd/mm/yyyy的形式输入日期,并将其转换为类似1986年8月26日的格式。 我被困在如何将我的月份(mm)从数字转换为文字。 下面是我目前的代码,希望你能帮助我。 **请不要建议使用日历功能,我们应该使用dict来解决这个问题

谢谢你(:


拆分日期字符串时,只有三个元素(0、1和2):

因此,日期[:2]将等于:

>>> day=date[:2] # that is, date up to (but not including) position 2
>>> print day
['11', '12']
和日期[4]将不存在,日期[3:5]也不存在

此外,您需要像这样调用字典值:

>>> print monthDict[12]
Dec
因此,要打印日、月、年组合,您需要执行以下操作:

>>> print date[0], monthDict[int(date[1])] + ", " + date[2]
11 Dec, 2012

您必须使用
int(日期[0])
作为
monthDict[int(日期[0])]
中的键,因为您使用整数作为字典键。但是您的输入(来自用户)是字符串,而不是整数。

完成拆分后,您不需要使用像day=date[:2]这样的索引。只需使用say=date[0]。类似地,匹配字典值不需要循环。您可以看到下面的代码

#allow the user to input the date
date=raw_input("Please enter the date in the format of dd/mm/year: ")

#split the strings
date=date.split('/')

#day
day=date[0]

#create a dictionary for the months
monthDict={1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'}
#month
monthIndex= int(date[1])

month = monthDict[monthIndex]
#year
year=date[2]
print day, month, "," , year 
运行时:

Please enter the date in the format of dd/mm/year: 1/5/2004
1 May , 2004

使用Python的datetime.datetime!使用
my_date=strTime(字符串“%d/%m/%Y”)
读取。使用
my_date.strftime(“%d%b,%Y”)打印它

访问:

例如:

import datetime
input = '23/12/2011'
my_date = datetime.datetime.strptime(input, "%d/%m/%Y")
print my_date.strftime("%d %b, %Y") # 23 Dec, 2011

避免将同一变量名用于不同目的(
date
在代码中)在一个代码块中;它会导致错误。@J.F.Sebastian好的,谢谢你^^是的,这是最具Python风格的答案。包括电池!yupps我在搜索hel做作业时多次遇到这个答案……但这对我们来说太“高层次”,我们还没有找到(;但还是非常感谢分享^^太感谢了^你真的让我很容易理解(:
date = raw_input("Please enter the date in the format of dd/mm/year: ")
date = date.split('/')
day = date[0] # date is, for example, [1,2,1998]. A list, because you have use split()
monthDict = {1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 
            7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'}
month = date[1] # Notice how I have changed this as well
                # because the length of date is only 3
month = monthDict[int(month)]
year = date[2] # Also changed this, otherwise it would be an IndexError
print day, month, "," , year
Please enter the date in the format of dd/mm/year: 1/5/2004
1 May , 2004
import datetime
input = '23/12/2011'
my_date = datetime.datetime.strptime(input, "%d/%m/%Y")
print my_date.strftime("%d %b, %Y") # 23 Dec, 2011