Jaakkath
Jaakkath

Reputation: 65

Python getting rid of a whitespace on a list

So, I came across this code, but I have 1 problem with it. When I run it, it leaves a whitespace after the sunday day of week. "Mo Tu We Th Fr Sa Su", I need help getting rid of the whitespace there. I've tried using .replace and .split, but so far they haven't helped. Thank you.

calendar1 = [('January', range(1, 31 + 1)),
            ('Feburary', range(1, 28 + 1)),
            ('March', range(1, 31 + 1)),
            ('April', range(1, 30 + 1)),
            ('May', range(1, 31 + 1)),
            ('June', range(1, 30 + 1)),
            ('July', range(1, 31 + 1)),
            ('August', range(1, 31 + 1)),
            ('September', range(1, 30 + 1)),
            ('October', range(1, 31 + 1)),
            ('November', range(1, 30 + 1)),
            ('December', range(1, 31 + 1))]

week = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su']

def make_calendar(year, start_day):

    # Determine current starting position on calendar
    start_pos = week.index(start_day)

    for month, days in calendar1:
        # Print month title
        print('{0} {1}'.format(month, year).center(20, ' '))
        # Print Day headings
        print(''.join(['{0:<3}'.format(w) for w in week]))
        # Add spacing for non-zero starting position
        print('{0:<3}'.format('')*start_pos, end='')

        for day in days:
            # Print day
            print('{0:<3}'.format(day), end='')
            start_pos += 1
            if start_pos == 7:
                # If start_pos == 7 (Sunday) start new line
                print()
                start_pos = 0 # Reset counter
        print('\n')

yr=int(input('Enter Year'))
strtday=input('Enter start day of the year Mo,Tu,We,Th,Fr,Sa,Su')
make_calendar(yr,strtday)

Upvotes: 0

Views: 108

Answers (3)

Laurent LAPORTE
Laurent LAPORTE

Reputation: 22942

To print the heading, I would use join to join the days, using a space as a separator:

        # Print Day headings
        print(' '.join(['{0:<2}'.format(w) for w in week]))

Your calendar is a table. To print each week, you can use a row that you fill with date. Once the row has 7 dates, you can print it:

        row = ['  '] * start_pos
        for day in days:
            row.append('{0:>2}'.format(day))
            if len(row) == 7:
                print(' '.join(row))
                row = []
        if row:
            print(' '.join(row))
        print()

Notice that you must consider the last day of the previous month when you print the calendar of the current month. There is a shifting… So, your algorithm is wrong. ;-)

Edit

You can use calendar module:

def format_day(day):
    return '{0:>2}'.format(day) if day else '  '

def print_calendar(year, month):
    c = calendar.Calendar()
    for week in c.monthdayscalendar(2018, 2):
        print(' '.join(map(format_day, week)))

print_calendar(2018, 2)

Upvotes: 1

fabianegli
fabianegli

Reputation: 2246

You can use .strip() or .rstrip() like so:

print(''.join(['{0:<3}'.format(w) for w in week]).strip())

Alternatively, construct the line without the "space in the end":

You basically format all week days to be printed with 3 characters which results in a string of length 21. Since there are only two letters in each abbreviation for the weekdays, and you format with the < to left align, you get a space. You can experiment with longer abbreviations to get see what is happening, e.g 'Sun' instead of 'Su'.

print(' '.join(['{0:<2}'.format(w) for w in week]))
       ↑             ↑
   glue/night   length of the 
                formatted string

The above approach directly generates a string of 20 characters: 7(weekdays)*2(characters per weekday)+6("nights").

Upvotes: 1

OldGeeksGuide
OldGeeksGuide

Reputation: 2918

If I understand correctly, you're printing the days of the week one at a time as you go and you want them to be 2 characters plus a space to separate them, so stripping the indivual days probably won't do what you want. You could change your code slightly to build the string until you have a whole line built, then print it, i.e. something like:

s = ''
... 
# Print day
s += f'{day:<3}'  # Using the new format string feature in 3.6, otherwise use old style format
if start_pos == 7:
    print(s.rstrip())  # Eliminate trailing whitespace
...

You might need to add a print after the loop exits as well, I didn't examine the exact semantics of your code, but something like this should work.

Upvotes: 1

Related Questions