Veerle
Veerle

Reputation: 43

Separating values by commas

I have the following code:

for n in range(1, 101):
    if 100 % n == 0:
        print(n, end='')

I want to print all divisors of 100. However, I want them in one line (which I accomplish by putting end='' in the code). On top of that, I want commas between the numbers. I want to have an output like this:

1, 2, 4, 5, 10, 20, 25, 50, 100

sep=',' does not work because of the loop it is in. end=',' will work, but this will lead to a comma after 100, which is not what I want.

Upvotes: 1

Views: 110

Answers (6)

Farhan.K
Farhan.K

Reputation: 3485

Try this:

mylist = []
mynumber = 100
for n in range(1,(int(mynumber/2))+1):
    if mynumber % n == 0:
        mylist.append(str(n))
mylist.append(mynumber)
print (','.join([str(item) for item in mylist]))

You don't need to try everything up to the number you are testing because it wont have a factor bigger than its half. E.g. 10 doesn't have a factor after 5 except 10 itself.

You can change "mynumber" to whichever number you wish to test.

Upvotes: 0

Veeresh Aradhya
Veeresh Aradhya

Reputation: 19

you can use string formatting for that

for n in range(1, 101):
if 100 % n == 0:
    print "%s," %n,

output

1, 2, 4, 5, 10, 20, 25, 50, 100,

Upvotes: 0

Jean Nassar
Jean Nassar

Reputation: 565

I don't have enough reputation to add a comment to Anand S Kumar, but I want to point out that you don't need a list inside join since it can take a generator expression. So you can also do:

>>> print(", ".join(str(n) for n in range(1, 101) if 100 % n == 0))
1, 2, 4, 5, 10, 20, 25, 50, 100

edit: I had a comment stating that this was faster. It turns out that this was incorrect.

Upvotes: 1

Anand S Kumar
Anand S Kumar

Reputation: 90889

You can create a list and then use str.join. For example:

lst = []
for n in range(1, 101):
    if 100 % n == 0:
        lst.append(str(n))
print(','.join(lst))

Example/Demo -

>>> lst = []
>>> for n in range(1, 101):
...     if 100 % n == 0:
...         lst.append(str(n))
...
>>>
>>> print(','.join(lst))
1,2,4,5,10,20,25,50,100

This can also be done in single line, by using a list comprehension:

print(','.join([str(n) for n in range(1, 101) if 100 % n == 0]))

Demo:

>>> print(','.join([str(n) for n in range(1, 101) if 100 % n == 0]))
1,2,4,5,10,20,25,50,100

Upvotes: 2

San k
San k

Reputation: 141

Try this

ls = []
for n in range(1, 101):
if 100 % n == 0:
    ls.append(str(n))

print (','.join(ls))

Upvotes: 0

Delgan
Delgan

Reputation: 19617

You need to store values into a list and then use .join(). Moreover, note that you have to cast elements in your list to string.

my_list = []
for n in range(1, 101):
    if 100 % n == 0:
        my_list.append(n)

print(", ".join(str(x) for x in my_list))

Upvotes: 1

Related Questions