我正在尝试输出日历上的日期,例如:2021-02-02 2021-02-03 2021-02-04 2021-02-05等。 我从https://www.tutorialbrain.com/python-calendar/复制了这段代码,所以我不明白为什么会出现错误
import calendar
year = 2021
month = 2
cal_obj = calendar.Calendar(firstweekday=1)
dates = cal_obj.itermonthdays(year, month)
for i in dates:
i = str(i)
if i[6] == "2":
print(i, end="")
错误:
if i[6] == "2":
IndexError: string index out of range
Process finished with exit code 1
如果您的目标是创建日历日期列表,则还可以使用以下选项:
您可以选择任何开始日期或结束日期(如果该日期存在)
您的代码和他们的代码之间存在差异。这很微妙,但它就在那里:
你的:
他们的:
^{} 以} 返回^{} s
int
s的形式返回月份的天数,而^{似乎您是python新手
i[6]
表示列表或类似列表的数据类型的元素的索引。 通过以下方式使用datetime库可以实现同样的功能输出
相关问题 更多 >
编程相关推荐