python密钥错误消息

2024-10-02 18:15:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在设法解决这个问题。这是问题和代码。 #编写一个接受两个输入的过程日期转换器。首先是 #一本字典,另一本是字符串。字符串是中的有效日期 #月/日/年格式。程序应该返回 #表格上写的日期。 #例如,如果 #字典是用英语写的

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

输出为: 没有 没有 没有 没有 注销

[流程已完成]

有什么问题吗。在


Tags: theto字符串date字典englishmayconverter
2条回答

在dict中,键是数字(而不是字符串)。在

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

这里不需要重新设计轮子,因为python带有“batteries included”。:-)

使用^{}模块。在

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方法将在区域设置中显示正确的月份名称。在

您可以使用^{}设置区域设置。所以对于瑞典语:

^{pr2}$

相关问题 更多 >