Printing List Shows Single Quote Mark
I have the following python code snippet: LL=[] for i in range(3): LL.append('a'+str(i)) print LL The output comes as: ['a0', 'a1', 'a2'] How can I print as (using print LL):
Solution 1:
You are printing the repr
format of the list. Use join
and format
instead
>>>print"[{}]".format(', '.join(LL))
[a0, a1, a2]
Solution 2:
Here's one utility function that worked for me:
defprintList(L):
# print list of objects using string representationif (len(L) == 0):
print"[]"return
s = "["for i inrange (len(L)-1):
s += str(L[i]) + ", "
s += str(L[i+1]) + "]"print s
This works ok for list of any object, for example, if we have a point class as below:
classPoint:
def__init__(self, x_crd, y_crd):
self.x = x_crd
self.y = y_crd
def__str__(self):
return"(" + str(self.x) + "," + str(self.y) + ")"
And have a list of Point objects:
L = []
for i in range(5):
L.append(Point(i,i))
printList(L)
And the output comes as:
[(0,0), (1,1), (2,2), (3,3), (4,4)]
And, it served my purpose. Thanks.
Post a Comment for "Printing List Shows Single Quote Mark"