How to convert a month number into a month name in python

user1887183 picture user1887183 · Dec 8, 2012 · Viewed 17.2k times · Source

How do you get a list to correspond with a user input. If I had a list like:

month_lst = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
              'August', 'September', 'October', 'November', 'December']

How do I get an input of 1 to return 'January' as the answer?

input('Enter the number to be converted: ')

Also the input needs to check with the list to make sure it is within 1-12, so inputing 15 would read an error message.

Answer

shannonman picture shannonman · Dec 8, 2012

The calendar library can provide what you want, see the documentation at http://docs.python.org/2/library/calendar.html

calendar.month_name[month_number] #for the full name 

or

calendar.month_abbr[month_number] #for the short name