将用户输入日期 (04 01 2014) 转换为(2014 年 1 月 4 日)

  • 本文关键字:2014 转换 用户 日期 python
  • 更新时间 :
  • 英文 :


我正在编写一个程序,用户将输入3个数字,分别是月份和年份,它将以2nd January 2014的格式输出。到目前为止,我已经做到了

 year =input("what year is it")
 month=int(input("what is the numerical value of the month"))
 day=input("what number day is it")
 if month == 1:
     January = str(month)
     if day == 1 or 21 or 31:
         print (day+"st January",year)
     elif day == 2 or 22:
         print (day+"nd January",year)
     elif day ==3 or 23:
         print (day+"rd January",year)
     elif day == 4 or 5 or 6 or 7 or 8 or 9 or 10 or 11 or 12 or 13 or 14 or 15 or 16 or 18 or 19 or 20 or 24 or 25 or 26 or 27 or 28 or 29 or 30:
         print (day+"th January",year)

我遇到的问题是,当我输入诸如 4 之类的一天时,它将输出为 2014 年 1 月 4 日。我正在使用python 3,并且已经学习了for和while循环以及if语句,如果有帮助的话

使用库和词典,要记住的一个好规则是,如果您需要两个以上的字典if可能会更好。

from datetime import date
ext_dir = {1:'st.', 2:'nd.', 3:'rd.',
    21:'st.', 22:'nd.', 23:'rd.',
    31:'st.' } # all the rest are th
# prompt for the year month day as numbers remember to int them
thedate = date(year, month, day)
ext = ext_dir.get(day, 'th.')
datestr = thedate.strftime('%%d%s %%M %%Y' % ext)

您遇到的问题是,当您执行检查时:

if day == 1 or 21 or 31:

Python 中的运算符优先级使此语句的行为如下所示:

if (day == 1) or (21) or (31):

在 Python 中,像许多其他语言一样,非空/非零值是"true",所以你在第一次测试中总是评估为 true。若要解决此问题,请修改 if 语句和以下所有测试,使其更类似于以下内容:

if (day == 1) or (day == 21) or (day == 31):
 year =input("what year is it")
 month=int(input("what is the numerical value of the month"))
 day=input("what number day is it")
 if month == 1:
     January = str(month)
     if day == 1 or day == 21 or day == 31:
         print (day+"st January",year)
     elif day == 2 or day == 22:
         print (day+"nd January",year)
     elif day ==3 or day == 23:
         print (day+"rd January",year)
     else:
         print (day+"th January",year)

最新更新