Reputation: 2529
I have the following code:
import calendar
month=calendar.month_name
print(month)
I wish to have following output which is in array form or list form:
['January','February',...,'December']
but above code return me nothing.
Anyone can point out my error?
Upvotes: 4
Views: 5577
Reputation: 59974
What it returns is actually an array object. If you want to convert it to a list, call list()
on it:
>>> import calendar
>>> calendar.month_name
<calendar._localized_month instance at 0x10e0b2830>
>>> list(calendar.month_name)
['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
By default the list has the empty string as its first element so that indexing may be done from 1 and not 0. If you want to remove this while still converting it to a list, just call calendar.month_name[1:]
Depending on your code, there might not actually need to be any reason to do this. The array object will have the same properties as any list:
>>> for month in calendar.month_name[1:]:
... print month
...
January
February
March
April
May
June
July
August
September
October
November
December
Upvotes: 9
Reputation: 4021
Use filter to get non-empty strings:
import calendar
months = filter(None, calendar.month_name)
Upvotes: 0
Reputation: 11550
>>>import calendar
>>>months = [x for x in calendar.month_name if x]
>>>print(months)
['January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December']
Upvotes: 2