Reputation: 35
I'm wondering if it was possible to add commas to numbers, with a for loop similar to this
for x in range(0,10):
print x
the output I am looking for is 0,1,2,3,4,5,6,7,8,9
Upvotes: 1
Views: 174
Reputation: 83
You can do this:
start = 0
end = 10
result = ""
for x in range(start,end+1):
result += str(x)
if x < (end):
result += ","
print(result) # $: '0,1,2,3,4,5,6,7,8,9,10'
Upvotes: 0
Reputation: 926
In Python 3 you may do it in one line:
print(*range(10),sep=',')
Result:
0,1,2,3,4,5,6,7,8,9
Upvotes: 0
Reputation: 22954
You may simply do it in 1 line as :
",".join(map(str, range(10)))
where, join()
method is used to concatenate the strings with the given character ","
(in this case) and map()
converts each integer from range(10)
to type str
.
Alternatively, if you want to use for
loop then you may simply concatenate the string using +
between the str(i)
and the ","
.
for i in range(10):
print str(i) + ",",
Upvotes: 6