Writing white-space delimited text to be human readable in Python

Jake picture Jake · Sep 11, 2010 · Viewed 9.7k times · Source

I have a list of lists that looks something like this:

data = [['seq1', 'ACTAGACCCTAG'],
        ['sequence287653', 'ACTAGNACTGGG'],
        ['s9', 'ACTAGAAACTAG']]

I write the information to a file like this:

for i in data:
    for j in i:
        file.write('\t')
        file.write(j)
    file.write('\n')

The output looks like this:

seq1   ACTAGACCCTAG  
sequence287653   ACTAGNACTGGG  
s9   ACTAGAAACTAG  

The columns don't line up neatly because of variation in the length of the first element in each internal list. How can I write appropriate amounts of whitespace between the first and second elements to make the second column line up for human readability?

Answer

Mark Tolonen picture Mark Tolonen · Sep 11, 2010

You need a format string:

for i,j in data:
    file.write('%-15s %s\n' % (i,j))

%-15s means left justify a 15-space field for a string. Here's the output:

seq1            ACTAGACCCTAG
sequence287653  ACTAGNACTGGG
s9              ACTAGAAACTAG