Protul
Protul

Reputation: 79

How can I remove whitespace after characters are encountered in Python

In my program the first line contains number of test-cases, other lines contain test-cases themselves. Each test-case contains 8 numbers, 4 for each timestamp: day1 hour1 min1 sec1 day2 hour2 min2 sec2 (second timestamp will always be later than first). Answer: for each test-case you are to output difference as following (days hours minutes seconds) - please note brackets - separated by spaces.

This is my code:

ins = int(input())

new_list = []

for i in range(ins):
    values = [int(x) for x in input().split()]

    if values[3] > values[7]:
        values[2] += 1
        seconds = 60 - (values[3] - values[7])

    else:
        seconds = values[7] - values[3]

    if values[2] > values[6]:
        values[1] += 1
        minutes = 60 - (values[2] - values[6])

    else:
        minutes = values[6] - values[2]

    if values[1] > values[5]:
        values[0] += 1
        hours = 24 - (values[1] - values[5])

    else:
        hours = values[5] - values[1]

    days = values[4] - values[0]

    new_list.append('(')
    new_list.append(days)
    new_list.append(hours)
    new_list.append(minutes)
    new_list.append(seconds)
    new_list.append(')')

print(' '.join(map(str,new_list)))

This is my input:

3
1 0 0 0 2 3 4 5
5 3 23 22 24 4 20 45
8 4 6 47 9 11 51 13

And this is my output:

( 1 3 4 5 ) ( 19 0 57 23 ) ( 1 7 44 26 )

My question is how can I remove the spaces after and before my brackets, so that my output looks like this:

(1 3 4 5) (19 0 57 23) (1 7 44 26)

Upvotes: 0

Views: 115

Answers (3)

TrakJohnson
TrakJohnson

Reputation: 2097

Another approach using the brand new formatted string literals (>= 3.6):

new_list.append(f'({days} {hours} {minutes} {seconds}) ')

Replaces this:

new_list.append('(')
new_list.append(days)
new_list.append(hours)
new_list.append(minutes)
new_list.append(seconds)
new_list.append(')')

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92894

In your simple case it can be simplified without even using str.join() and map() functions:

result = ""
for i in range(ins):
    ...
    result += '(' + str(days) +" "+ str(hours) + " "+ str(minutes) +" "+ str(seconds) +") "

Or by using format() function:

    result += '({} {} {} {}) '.format(days, hours, minutes, seconds)

The output:

(1 3 4 5) (19 0 57 23) (1 7 44 26)

Upvotes: 2

Zak
Zak

Reputation: 2078

Perhaps not the most elegant solution, but change your final line to look like this.

print(' '.join(map(str,new_list)).replace('( ', '(').replace(' )', ')'))

Upvotes: 3

Related Questions