到目前为止,我有以下内容:
month_list = ['January', 'February', 'March', 'April',
'May', 'June', 'July', 'August', 'September',
'October', 'November', 'December']
for i, value in enumerate(month_list, 1):
print(i, value)
但是,我希望输出看起来像:
Month 1 is January Happy New Year!
依此类推,直到十二月。
执行类似的操作:f向python表示它是格式化的字符串,因此它将用变量值替换{}之间的任何内容。
for i in range(len(month_list)):
print(f'Month {i+1} is {month_list[i]}')
您可以使用f字符串在循环中轻松设置格式。然后对计数进行简单检查,例如,如果您要在某些月份中向字符串添加一些额外内容。
for i, value in enumerate(month_list, 1):
s = f"Month {i} is {value}"
if i == 1:
s += " Happy New Year!"
print(s)
输出
Month 1 is January Happy New Year!
Month 2 is February
Month 3 is March
Month 4 is April
Month 5 is May
Month 6 is June
Month 7 is July
Month 8 is August
Month 9 is September
Month 10 is October
Month 11 is November
Month 12 is December
请注意,Python没有switch语句,因此,如果您想在不同月份有更多发言权,则只需使用一堆elif语句。