Skip to main content
 首页 » 编程设计

python之如何打印全年日历(2019)

2025年05月04日18mq0036

我正在尝试打印 2019 年的整个日历。我可以打印日历,但我想在所有月份之前打印年份,例如:

January 2019 

但是输出是这样的:

2019 
 
January 

这是我的代码:

import calendar 
 
def printcalendar(year): 
     print(calendar.calendar(2019,1,1,1,1)) 
 
year = 2019 
printcalendar(year) 

请您参考如下方法:

由于日历结构良好,您可以编写自己的函数来按照您的需要设置格式。您的函数应完成以下任务:

  1. 去掉字符串开头的年份
  2. 删除过去在年份和一月之间的额外新行
  3. 用月+年替换每个月
  4. 打印结果

这很简单。

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.