Home > Software design >  How to remove last whitespace of a single line output inside a loop?
How to remove last whitespace of a single line output inside a loop?

Time:09-22

I want my output to be in a single line that's why I was using end = ' ' but since it is in a loop, It also adds space after the last value which I don't want. I tried using strip() but it removes every space. so How do I remove the last space from my output in that loop?

import math

f0 = int(input())
r = math.pow (2, 1/12)
for i in range(5):
    f1 = f0 * (r ** i )
    print('{:.2f}'.format(f1), end= ' ')

Expected Output: If 440 is Input 440.00 466.16 493.88 523.25 554.37

My Output :440.00 466.16 493.88 523.25 554.37

CodePudding user response:

Consider replacing your for loop with a generator expression along with str.join like so:

print(' '.join((f'{f0*r**i:.2f}' for i in range(5))))

Output: 440.00 466.16 493.88 523.25 554.37

This approach saves you from having to have different behaviour on the last iterator of the loop, or editing the string afterwards.

str.join inserts the string (' ' in this case) between each element of the iterable, but not at the beginning or end.

CodePudding user response:

You can add a if-else statement and apply it for the last iteration of the loop.

import math

f0 = int(input())
r = math.pow(2, 1/12)
for i in range(5):
    f1 = f0 * (r ** i )
    if i == 5:
        print('{:.2f}'.format(f1))
    else:
        print('{:.2f}'.format(f1), end= ' ')
  • Related