0

I have this function which is printing out all odd numbers between 1 and 100. I want a comma , between all numbers except the last one 99

for i in range(1,100,2):
    print(str(i), end=',')

What I got:

1, 3, 5, 7, 9, 11, 13, 15 ... 97, 99,

What I want:

1, 3, 5, 7, 9, 11, 13, 15 ... 97, 99

shad0w_wa1k3r
  • 12,955
  • 8
  • 67
  • 90
aregato
  • 3
  • 1
  • 3

2 Answers2

4

You can use str.join to inject delimiters between values, which you can create using a generator expression as follows

>>> ', '.join(str(i) for i in range(1,100,2))
'1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99'
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • Nice thanks! I was looking for a way to do it like this (see below) but it doesnt work. Dont Think i understand it. for i in range(1,100,2): print(', '.join(str(i)) – aregato Aug 27 '17 at 12:49
0

string = ""

for i in range(100):

if i == 99:

    string = string + str(i)

else:

    string = string + str(i) + ","

print string

roye1233
  • 110
  • 2
  • 13