简体   繁体   English

在Python中编写以空白分隔的文本是人类可读的

[英]Writing white-space delimited text to be human readable 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 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? 如何在第一个和第二个元素之间编写适当数量的空白以使第二列符合人类可读性?

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. %-15s表示左对齐字符串的15空格字段。 Here's the output: 这是输出:

seq1            ACTAGACCCTAG
sequence287653  ACTAGNACTGGG
s9              ACTAGAAACTAG
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 对我来说,比循环表达更清晰

"%10s" % obj will ensure minimum 10 spaces with the string representation of obj aligned on the right. "%10s" % obj将确保最少10个空格,并在右侧对齐obj的字符串表示。

"%-10s" % obj does the same, but aligns to the left. "%-10s" % obj执行相同操作,但与左侧对齐。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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