python根據給定的年月日以數字形式列印日期
阿新 • • 發佈:2019-01-03
months=[
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
]
以1-31的數字作為結尾的列表,定義的endings變數賦值後面加上17*和7*,
原來該變數定義的是1-31這31個數的英文字尾,這31個數的英文是1:first 2:second 3:third
4:fourth 5:fifth 6:sixth 7:seventh 8:eighth 9:ninth 10:tenth 11:eleventh 12:twelfth 13:thirteenth 14:fourteenth 15:fifteenth
16:sixteenth 17:seventeenth 18:eighteenth 19:ninteenth 20:twentieth21:twentyfirst 22:twenty-second 23:twenty-third24:twenty-fourth 25:twenty-fifth 26:twenty-sixth 27;twenty-seventh 28:twenty-eighth 29:twenty-ninth 30:thirtieth 31:thirty-first
其中在第一個 [‘st’,’nd’,’rd’]後面從fourth到twentieth一共是17個‘th’,然後是又一個[‘st’,’nd’,’rd’]後面再從twenty-fourth到thirtieth一共是7個‘th’,17 * [‘th’]的意思就是:給這個資料新增17個’th’字串
endings=['st','nd','rd']+17*['th']\
+['st','nd','rd']+7*['th']\
+['st']
獲取使用者輸入的日期資訊
year =raw_input('Year: ')
month =raw_input('Month(1-12): ')
day =raw_input('Day(1-31): ')
將月份和日期轉化成整數
month_number=int(month)
day_number=int(day)
因為索引從0開始所以取到的月份和天數會往後推一個月,獲取當前的日期需要減一 ,例如:輸入month_name 3 ,取到的是April四月,實際上我們想要的是三月
month_name=months[month_number-1]
ordinal=day+endings[day_number-1]
列印日期
print month_name+' '+ordinal+'.'+year