Cameron
Cameron

Reputation: 11

How do I delete the last space in the final output?

a = input().split()

for i in a:
    c = int(i)
    if c > 0:        
        b = c - 4
        d = b % 10
        if d != 0:
            print(i, "",  end='')
    else:
        e = c + 4
        f = e % 10
        if f != 0:
            print(i, "", end='')

This the whole code

The expected final output should be integers with space in between but no space at the end

By adding "" I got spaces in between the elements.

So, how do I delete the space after the final, last element.

Upvotes: 1

Views: 68

Answers (3)

KJDII
KJDII

Reputation: 861

You can append your results to a list and then print the list.

results = []
for i in a:
    c = int(i) 
    if c > 0:           
        b = c - 4    
        d = b % 10     
        if d != 0:        
            results.append(i)
    else:   
        e = c + 4
        f = e % 10
        if f != 0:
            results.append(i)

print(*results)

Upvotes: 1

TheEagle
TheEagle

Reputation: 5992

Or, if you do not want to create a list, you can count the elements, and use an if else statement to determine if it's the last element or not.

a = input().split()

for counter, i in enumerate(a):
    c = int(i)
    if c > 0:        
        b = c - 4
        d = b % 10
        if d != 0:
            if counter < len(a) - 1:
                print(i, "",  end='')
            else:
                print(i, end='')
    else:
        e = c + 4
        f = e % 10
        if f != 0:
            if counter < len(a) - 1:
                print(i, "", end='')
            else:
                print(i, end='')

Upvotes: 0

Marsolgen
Marsolgen

Reputation: 187

I would suggest you store all you values to print in a list (so instead of print you append them to a list) and the at the end

print(*list)

Which will print each of the elements with a space in between.

Upvotes: 1

Related Questions