Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the trailing comma from a loop in Python?

Here is my code so far:

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

The IsPrime function calculates whether or not a function is prime.

I need to print out the prime numbers from 1 to 100 formatted into a single line with commas and spaces in between. for example, output should look like:

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 I always get a trailing comma at the end of 97. I don't know how to remove the comma, and because it is a loop, str.rstrip and [:-1] don't work.

I need to use a loop and I can't use

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

for the other prime numbers.

I can't tell if there's an easier way to code this or I'm not aware of a function that can do this correctly.

like image 985
Leroy Gerrod Avatar asked Jul 19 '15 20:07

Leroy Gerrod


People also ask

How do you remove the comma at the end of a for loop in Python?

You can use ', '.

How do I remove a trailing comma from a string?

To remove the leading and trailing comma from a string, call the replace() method with the following regular expression as the first parameter - /(^,)|(,$)/g and an empty string as the second.


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

(Things would be better if IsPrime actually returned True or False instead of a string)

This is functional instead of imperative code.

If you want imperative code, you should print the ', ' before each element excepting the first item of the loop. You can do this with a boolean variable which you set to true after you've seen one item.

like image 145
Borealid Avatar answered Nov 15 '22 06:11

Borealid


You can put all the numbers into a list and then join all the values:

def main():
    primes = []
    for var in range (1, 101):
        if IsPrime(var) == 'true':
            primes.append(var)
        num = IsPrime(var)
    print(', '.join(primes))
like image 34
Daniele Pantaleone Avatar answered Nov 15 '22 08:11

Daniele Pantaleone