Reputation: 367
My list produces the following output: (running Python 3.4)
('MSG1', 3030)
('MEMORYSPACE', 3039)
('NEWLINE', 3040)
('NEG48', 3041)
Is there any way to make all the numbers line up like a column? Thanks. My code is a simple print statement:
for element in data:
print (element)
Upvotes: 2
Views: 2275
Reputation: 16711
You can justify according to the longest word:
longest = max([len(x[0]) for x in data])
for j in data:
a = j[0].ljust(longest)
b = str(j[1])
print(' '.join([a, b]))
Here is the output:
MSG1 3030
MEMORYSPACE 3039
NEWLINE 3040
NEG48 3041
Upvotes: 5
Reputation: 18148
Have you tried format?
max_len = max([len(x[0]) for x in data])
for element in data:
print '{value0:{width0}} {value1}'.format(value0=element[0],
width0=max_len,
value1=element[1])
Sample output:
MSG1 3030
MEMORYSPACE 3039
NEWLINE 3040
NEG48 3041
You could also right-justify by adding >
to the format specifier:
...
print '{value0:>{width0}} {value1}'.format(
...
Produces:
MSG1 3030
MEMORYSPACE 3039
NEWLINE 3040
NEG48 3041
Upvotes: 4
Reputation: 4580
I would print the number first, if possible:
for i in lst:
print i[1],'\t',i[0]
Upvotes: 0
Reputation: 174706
You could try the below. Since the second element is an integer value, you need to convert it into string
type before printing.
>>> for x,y in data:
print(x+"\t"+str(y))
MSG1 3030
MEMORYSPACE 3039
Upvotes: 0
Reputation: 19264
You can use '\t'
:
for element in data:
print str(element[0])+'\t'+str(element[1])
MSG1 3030
MEMORYSPACE 3039
NEWLINE 3040
NEG48 3041
Unfortunately, because your first elements are sometimes longer, try printing the number first:
for element in data:
print str(element[1])+'\t'+str(element[0])
3030 MSG1
3039 MEMORYSPACE
3040 NEWLINE
3041 NEG48
Upvotes: 0