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

自古美人都是妖i 提交于 2019-12-06 06:03:17

问题


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?


回答1:


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



回答2:


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 is even clearer than expression with loop




回答3:


"%10s" % obj will ensure minimum 10 spaces with the string representation of obj aligned on the right.

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



来源:https://stackoverflow.com/questions/3689936/writing-white-space-delimited-text-to-be-human-readable-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!