如何使一个数字列表在某一点的换行? [英] How Do I Make a List of Numbers Line Break at a Certain Point?

查看:183
本文介绍了如何使一个数字列表在某一点的换行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个程序来打印出一个日历,打印输出的日期与他们的日期一致。我几乎已经解决了,但我不知道如何使数字在星期天后打破一个新的行。现在代码如下:

I am trying to write a program to print out a calendar that will print out the numbers in line with the days they fall on. I have it almost worked out, but I don't know how to make the numbers break to a new line after Sunday. Right now the code looks like this:

class Month:
    def __init__(self, nDays, day1):
        self.nDays = nDays
        self.day1 = day1

    def displayCalendar(self):
        week = ' S  M  T  W  T  F  S '
        print week
        days = 1
        if self.day1 == 2:
            print '  ',
        elif self.day1 == 3:
            print '     ',
        elif self.day1 == 4:
            print '        ',
        elif self.day1 == 5:
            print '           ',
        elif self.day1 == 6:
            print '              ',
        elif self.day1 == 7:
            print '                 ',

        for i in range(self.nDays):
            print '', days,
            days = days + 1

print '     APRIL 2014'
april2014 = Month(30,3)
april2014.displayCalendar()

现在,我可以在适当的一天开始这个月,但数字只是继续在屏幕的边缘,不要回到星期一。我知道这可能是一些愚蠢的细节,但我不能想出来为我的生活。

As it stands now, I can start the month on the proper day, but the numbers just continue off the edge of the screen and don't come back to Monday.I know it is probably some stupid little detail, but I can't figure it out for the life of me.

推荐答案

以下代码将生成所需的结果(注意:它使用字符串格式):

The following code will produce the desired result (note: it makes use of string formatting):

class Month:
    def __init__(self, nDays, day1):
        self.nDays = nDays
        self.day1 = day1

    def displayCalendar(self):
        week = ' S  M  T  W  T  F  S '
        print week
        days = 1
        if self.day1 == 2:
            print '  ',
        elif self.day1 == 3:
            print '     ',
        elif self.day1 == 4:
            print '        ',
        elif self.day1 == 5:
            print '           ',
        elif self.day1 == 6:
            print '              ',
        elif self.day1 == 7:
            print '                 ',

        for i in range(self.nDays):
            print '{:2}'.format(days),
            if (self.day1 + i) % 7 == 0:
                print ''
            days = days + 1

print '     APRIL 2014'
april2014 = Month(30,3)
april2014.displayCalendar()







[OUTPUT]
      APRIL 2014
 S  M  T  W  T  F  S 
       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

这篇关于如何使一个数字列表在某一点的换行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆