python密钥错误消息

时间:2012-12-29 20:17:22

标签: python key

我正在努力解决这个问题。这是问题和代码。     #编写一个带有两个输入的过程date_converter。首先是     #一个字典,第二个字符串。该字符串是有效的日期     #格式月/日/年。该程序应该返回     #表格中写的日期。     #例如,如果     #dictionary是英文的,

english = {1:"January", 2:"February", 3:"March", 4:"April", 5:"May", 
6:"June", 7:"July", 8:"August", 9:"September",10:"October", 
11:"November", 12:"December"}

# then  "5/11/2012" should be converted to "11 May 2012". 
# If the dictionary is in Swedish

swedish = {1:"januari", 2:"februari", 3:"mars", 4:"april", 5:"maj", 
6:"juni", 7:"juli", 8:"augusti", 9:"september",10:"oktober", 
11:"november", 12:"december"}

# then "5/11/2012" should be converted to "11 maj 2012".

# Hint: int('12') converts the string '12' to the integer 12.

def date_converter(dic, n):
    theSplit = n.split("/")
    a = theSplit[0]
    b = theSplit[1]
    c = theSplit[2]
    if a in dic:
        return b + " " + dic[theM] + " " + c
    else:
        return None

print date_converter(english, '5/11/2012')
#>>> 11 May 2012

print date_converter(english, '5/11/12')
#>>> 11 May 12

print date_converter(swedish, '5/11/2012')
#>>> 11 maj 2012

print date_converter(swedish, '12/5/1791')
#>>> 5 december 1791

输出是:     没有     没有     没有     没有     注销

[已完成处理]

问题是什么。

2 个答案:

答案 0 :(得分:1)

你不必在这里重新发明轮子,因为python附带了“batteries included”。 :-)

使用datatime模块。

In [23]: import datetime

In [24]: d = datetime.date(2012, 5, 11)

In [25]: d.strftime('%d %b %Y')
Out[25]: '11 May 2012'

strftime方法将输出在语言环境中设置的正确月份名称。

您可以使用locale.setlocale()设置区域设置。瑞典语:

In [30]: locale.normalize('sv')
Out[30]: 'sv_SE.ISO8859-1'

In [31]: locale.setlocale(locale.LC_ALL, locale.normalize('sv'))
Out[31]: 'sv_SE.ISO8859-1'

In [32]: d.strftime('%x')
Out[32]: '2012-05-11'

In [33]: d.strftime('%d %b %Y')
Out[33]: '11 Maj 2012'

答案 1 :(得分:0)

在你的词典中,键是数字(不是字符串)。

def date_converter(dic, n):
    theSplit = n.split("/")
    a = theSplit[0]
    b = theSplit[1]
    c = theSplit[2]
if int(a) in dic:
    return b + " " + dic[int(a)] + " " + c
else:
    return None