我正在尝试编写将月份编号转换为月份名称的代码

时间:2020-03-15 18:26:46

标签: python list

到目前为止,我想出了这段代码,是将月份的dd / yyyy读出为dd,yyyy,我该怎么做才能使代码的翻译工作正常?

date = input('Please enter a date in mm/dd/yyyy format: ')
month_list = ['January', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'November', 'December']

if date[0] == 0:
      month_num = date[1]
      print(month_list[month_num])
else:
      month_num = (date[0] *10) + date[2]
      print(month_list[month_num])

1 个答案:

答案 0 :(得分:0)

您处在正确的轨道上。您的问题之一是索引位置从0开始,您的索引位置错误。您还误认为列表中的2月和10月。这应该起作用:

date = input('Please enter a date in mm/dd/yyyy format: ')
month_list = ['January', "February",'March', 'April', 'May', 'June', 'July', 'August', 'September', "October", 'November', 'December']

if date[0] == '0':
    month_num = int(date[1])
    print(month_list[month_num - 1])
else:
    month_num = (int(date[0]) *10) + int(date[1])
    print(month_list[month_num - 1])