Python,打印选项的次数

时间:2012-05-16 15:45:13

标签: python date

我是编码的新手,我的程序出了问题。我必须从文件中获取销售信息并以特定格式打印。这是代码:

#Looping program to read file per line
for line in lines:
    # Formatting line to read later
    line = line.strip().split(',')
    year = line[0]
    year = int(year)
    month = line[1]
    month = int(month)
    day = line[2]
    day = int(day)
    linePoint = date(year, month, day)

    cost = line[3]
    cost = float(cost)

    #Finding the lines within the start and end date
    if (linePoint >= startDate) and (linePoint <= endDate):
        printcost = (cost / 100)
        printcost = int(printcost)

        print "%s.%s.%s" % (startYear, startMonth, startDay)
        print "0%s:" % printNum,  "*" * printcost

        newcost = newcost + cost
        printNum += 1

当我使用%s.%s.%s打印销售日期以上的日期时,我希望它每月在其他打印声明上方打印一次,并且能够在月份结束时增加它。 同样在print "0%s:" % printNum, "*" * printcost语句中我希望它只打印前九天的零。

基本上我的问题是如何在Python中运行某些次数,但次数取决于用户并与日期相关,为此,计算机需要能够识别日期。抱歉模糊不清。

2 个答案:

答案 0 :(得分:1)

如果您希望输出为'01', '02', ..., '10', '11', ...,则您要使用的格式为:

print "%02d" % printNum

至于在每个新月开始时打印标题(这就是我正在阅读你问题的第一部分,你可以这样做:

old_month = 0
for line in lines:
    # do stuff
    month = whatever...
    if month != old_month:
        # print header here
        old_month = month
    #rest of loop

答案 1 :(得分:0)

我几乎可以肯定这就是你想要的。请注意“%02d”format specifier,它会为您提供前导零,并检查月份是否已通过if month != current_month更改。

current_month, print_num, new_cost = None, 0, 0

for line in lines:
    fields = line.strip().split(',')
    year = int(fields[0])
    month = int(fields[1])
    day = int(fields[2])
    cost = float(fields[3])

    line_date = date(year, month, day)

    #Finding the lines within the start and end date
    if startDate <= line_date <= endDate:
        if month != current_month:
            print "%s.%s.%s" % (year, month, day)
            current_month = month

        print_cost = int(cost / 100)
        print "%02d: %s" % (print_num,  "*" * print_cost)

        new_cost += cost
        print_num += 1