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)))
x = 'result is: ';
for i in range(0,5):
x += str(i) + ',';
print(x[:-1];
will do what you want. In a highly legible form although not the best speed possible.
Another version of the same thing:
for i in range(0,5):
if i == 0:
print "result is %d" % i,
else:
print ",%d" % i,
In Python3 you can use the end
kwarg of the print
function. This is not possible in Python2.
print("The result is: ", end="")
for i in range(5):
print(str(i)+", ", end="")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.