I have my code:
for i in range(0,5):
print "result is:"+str(i),
This prints:
result is:0 result is:1 result is:2 result is:3 result is:4
I want to print like this:
result is:0,1,2,3,4
How to do it in python?
print('Result is: {}'.format(', '.join(map(str, range(5)))))
prints
Result is: 0, 1, 2, 3, 4
Valid for Python 2 and Python 3.
Explanation:
range(5) is the same as range(0, 5). map(str, x), given an iterable x, returns a new iterable having all the items in x stringified (e -> str(e) ). ', '.join(iterable) joins a given iterable (list, generator, etc) whose elements are strings, into a string 1 string using the given separator. Finally str.format() replaces the {} placeholders with its arguments in order.
Since you want to print all the elements of the list, you can convert all the numbers to string and join all of them together with ,, like this
print "result is:" + ",".join(str(number) for number in range(0, 5))
Since the range's default start parameter is 0, you can call it like this
print "result is:" + ",".join(str(number) for number in range(5))
Also, you can use templated strings like this
print "result is: {}".format(",".join(str(number) for number in range(5)))
You can apply the str function to all the elements of the number list, with map function, like this
print "result is: {}".format(",".join(map(str, range(5)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With