2

I want to print the result output in the form of separated by a comma but i am getting a comma in last value also so how can i remove that.

import math

    d = input().split(',')
    d = [int(i) for i in d]
    c=50
    h=30
    result=[]
    for i in d:
        q=int(round(math.sqrt((2*c*i)/h)))
        result.append(q)
    for i in result:
        print(i, end=",")

here is an example of input i give and output i get

input : 10,20,30,40
output : 6,8,10,12,

how can i avoid getting that last comma

Aman
  • 131
  • 2
  • 11

3 Answers3

11

Pass the results as separate arguments and specify the separator:

 print(*result, sep=',')
wim
  • 338,267
  • 99
  • 616
  • 750
2

You could use join to join list elements on comma:

print(', '.join(map(str, result)))
Austin
  • 25,759
  • 4
  • 25
  • 48
1

wim's answer is the right one for your question, but a more generalized approach can be used in other situations. This approach is:

Instead of printing the separator after each item and trying to suppress the last one, print the separator before each item and suppress the first one.

This is simpler because it doesn't require being able to detect the last item being printed. Instead you set the separator to empty before entering the loop, and then after printing, change the separator to comma. (In the example below, I use string formatting; same idea.)

fmt = "%s"
for i in result:
    print(fmt % i, end="")
    fmt = ",%s"
kindall
  • 178,883
  • 35
  • 278
  • 309