简体   繁体   中英

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.

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.

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)

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='')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM