Reputation: 93
A similar question with Print new output on same line, which does not answer my question.
I wonder how (with python 2 and 3) to print all to one line. e.g., By running:
print("Result of:\t")
mylist1=[]
mylist2=[]
name = "class_1"
for i in range(-5, 0):
mylist1.append(i)
for j in range(1, 6):
mylist2.append(j)
print(name+"\t")
print(mylist1+"\t"+mylist2)
What I got:
Result of:
class_1
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-100-1e34909da6d3> in <module>
10 mylist2.append(j)
11 print(name+"\t")
---> 12 print(mylist1+"\t"+mylist2)
13
TypeError: can only concatenate list (not "str") to list
However, what I want is to print them in one line separated with "\t":
Result of: class_1 [-5, -4, -3, -2, -1] [1, 2, 3, 4, 5]
which solution is usually used for this case?
Upvotes: 1
Views: 1809
Reputation: 687
For python 3.x
print(name, sep="\t")
For python 2.x (in python 2.x print is not a function rather it is keyword)
Still achieve the same in python 2.x
from __future__ import print_function
print_function(name, sep="\t")
or
print "\t".join(list[name])
for python 3.x
print("Result of:", name, str(mylist1), str(mylist2), sep='\t')
for python 2.x
print "\t".join([name, str(mylist1), str(mylist2)])
Upvotes: 1
Reputation: 1088
mylist1=[]
mylist2=[]
name = "class_1"
for i in range(-5, 0):
mylist1.append(i)
for j in range(1, 6):
mylist2.append(j)
print("Result of:", name, str(mylist1), str(mylist2), sep='\t')
Upvotes: 1
Reputation: 3519
sep
argument to different values without using +
.list
to str
to print with []
mylist1=[]
mylist2=[]
name = "class_1"
for i in range(-5, 0):
mylist1.append(i)
for j in range(1, 6):
mylist2.append(j)
print("Result of:", name, str(mylist1), str(mylist2), sep='\t')
Upvotes: 3