Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 963
user1887183 Avatar asked Dec 08 '12 04:12

user1887183


2 Answers

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
like image 172
shannonman Avatar answered Oct 12 '22 09:10

shannonman


month_lst = ['January', 'Feburary', 'March', 'April', 'May', 'June', 'July', 
              'August', 'September', 'October', 'November', 'December']
try:
    month = int(input('Enter the number to be converted: '))
    if month < 1 or month > 12:
        raise ValueError
    else:
        print(month_lst[month - 1])
except ValueError:
    print("Invalid number")
like image 29
Hugo Avatar answered Oct 12 '22 09:10

Hugo