Writing text with limited reading space in Python

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 as follows:

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

The result is as follows:

 seq1 ACTAGACCCTAG sequence287653 ACTAGNACTGGG s9 ACTAGAAACTAG 

Columns are not built neatly due to a change in the length of the first element in each internal list. How can I write the appropriate number of spaces between the first and second elements to make a second column for readability?

+4
source share
3 answers

You need a format string:

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

%-15s means left is equal to 15 space for the string. Here's the conclusion:

 seq1 ACTAGACCCTAG sequence287653 ACTAGNACTGGG s9 ACTAGAAACTAG 
+10
source
 data = [['seq1', 'ACTAGACCCTAG'], ['sequence287653', 'ACTAGNACTGGG'], ['s9', 'ACTAGAAACTAG']] with open('myfile.txt', 'w') as file: file.write('\n'.join('%-15s %s' % (i,j) for i,j in data) ) 

for me even clearer than an expression with a loop

+1
source

"%10s" % obj will provide a minimum of 10 spaces with the string representation of obj aligned to the right.

"%-10s" % obj does the same, but aligns to the left.

0
source

All Articles