我正在尝试打印2019年的整个日历。我能够打印日历,但是我想在所有月份的前面打印年份,例如:
PreConditions
但是输出就像:
January 2019
这是我的代码:
2019
January
答案 0 :(得分:2)
由于日历结构合理,因此您可以编写自己的函数以按自己的意愿格式化它。您的函数应完成以下任务:
这很容易。
import calendar
def print_calendar(year):
months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]
cal_string = calendar.calendar(year, 1, 1, 1, 1)
cal_string = cal_string.strip() # Removes the leading and trailing whitespaces
cal_string = cal_string.replace(str(year), "") # Removes all occurences of the year
cal_string = cal_string[2:] # Removes the extra newlines at the beginning
for month in months:
cal_string = cal_string.replace(f" {month}", f"{month} {year}") # Replaces each month with the month and the year.
# We added the two spaces before month so that it's centered
print(cal_string)
return
print_calendar(2019)
输出:
January 2019
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
February 2019
Mo Tu We Th Fr Sa Su
1 2 3
... and so on
编辑:f-strings
是Python 3.6中引入的。如果您在此之前使用的是python版本,则必须替换行读数
cal_string = cal_string.replace(f" {month}", f"{month} {year}") # Replaces each month with the month and the year.
使用
cal_string = cal_string.replace(" {}".format(month), "{} {}".format(month, year)) # Replaces each month with the month and the year.
答案 1 :(得分:2)
使用print(calendar.__file__)
,您可以看到包含此模块源代码的文件路径。
要显示月份名称,它使用代码
class TextCalendar(Calendar):
def formatmonthname(self, theyear, themonth, width, withyear=True):
"""
Return a formatted month name.
"""
s = month_name[themonth]
if withyear:
s = "%s %r" % (s, theyear)
return s.center(width)
,它使用withyear=
来决定是否显示年份。
如果我创建自己的不含if withyear:
的课程,那么它将始终打印年份。
我还必须将calendar.
添加到calendar.month_name
import calendar
class MyCalendar(calendar.TextCalendar):
def formatmonthname(self, theyear, themonth, width, withyear=True):
s = calendar.month_name[themonth]
s = "%s %r" % (s, theyear)
return s.center(width)
c = MyCalendar()
print(c.formatyear(2019,1,1,1,1))
答案 2 :(得分:1)
此解决方案与版本的python版本无关
。@SyntaxVoisupportsMonica的解决方案对于任何<3.6的python都将失败。
此解决方案将打印您想要的月份,即m=[5]
将打印5月。
结论。使用这个:
import calendar
def mymonth(y,m):
for i in m:
print(calendar.month(y,i))
# second argument should be a list
mymonth(2019, [5,6])
打印:
May 2019
Mo Tu We Th Fr Sa Su
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
June 2019
Mo Tu We Th Fr Sa Su
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30