Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print out calendar.month_name array in python?

Tags:

python

arrays

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?

like image 295
Shi Jie Tio Avatar asked Dec 19 '22 05:12

Shi Jie Tio


1 Answers

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
like image 129
TerryA Avatar answered Jan 05 '23 15:01

TerryA