Shi Jie Tio
Shi Jie Tio

Reputation: 2529

How to print out calendar.month_name array in python?

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

Answers (3)

TerryA
TerryA

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

Use filter to get non-empty strings:

import calendar
months = filter(None, calendar.month_name)

Upvotes: 0

Rahul
Rahul

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

Related Questions