简体   繁体   中英

Python: Is there a way to pretty-print a list?

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) 

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

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

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

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

I would print the number first, if possible:

for i in lst:
    print i[1],'\t',i[0]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM