How to remove trailing comma from a loop in Python?

Here is my code:

def main(): for var in range (1, 101): num= IsPrime(var) if num == 'true': print(var, end=', ') 

The IsPrime function calculates whether the function is simple.

I need to print primes from 1 to 100, formatted on one line with commas and spaces between them. for example, the output should look like this:

 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 

I tried to run my program, but at the end of 97 I always get the final comma. I do not know how to remove a comma, and because it is a loop, str.rstrip and [: -1] do not work.

I need to use a loop and I cannot use

 print('2') print(', ', var, end='') 

for other prime numbers.

I can’t say if there is an easier way to encode this or I don’t know about a function that can do it right.

+6
source share
2 answers

The idiomatic Python code, in my opinion, would look something like this:

  print (',' .join ([str (x) for x in xrange (1, 101) if IsPrime (x) == 'true']))

(It would be better if IsPrime actually returned True or False instead of the string)

This is functional instead of imperative code.

If you need peremptory code, you must type ', ' before each element except the first element of the loop. You can do this with a boolean variable that you set to true after you see one element.

+9
source

You can put all numbers in a list and then concatenate all values:

 def main(): primes = [] for var in range (1, 101): if IsPrime(var) == 'true': primes.append(var) num = IsPrime(var) print(', '.join(primes)) 
+4
source

All Articles