在 Python 中编写以空格分隔的文本以供人类阅读 [英] Writing white-space delimited text to be human readable in Python
本文介绍了在 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')
输出如下:
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
表示左对齐字符串的 15 个空格字段.这是输出:
%-15s
means left justify a 15-space field for a string. Here's the output:
seq1 ACTAGACCCTAG
sequence287653 ACTAGNACTGGG
s9 ACTAGAAACTAG
这篇关于在 Python 中编写以空格分隔的文本以供人类阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文