在 Python 中编写人类可读的空白分隔文本
我有一个看起来像这样的列表列表:
data = [['seq1', 'ACTAGACCCTAG'],
['sequence287653', 'ACTAGNACTGGG'],
['s9', 'ACTAGAAACTAG']]
我将信息写入这样的文件:
for i in data:
for j in i:
file.write('\t')
file.write(j)
file.write('\n')
输出看起来像这样:
seq1 ACTAGACCCTAG
sequence287653 ACTAGNACTGGG
s9 ACTAGAAACTAG
由于每个内部列表中第一个元素的长度不同,列排列不整齐。如何在第一个和第二个元素之间写入适量的空格以使第二列对齐以便于人类可读?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要一个格式字符串:
%-15s
表示左对齐字符串的 15 个空格字段。这是输出:You need a format string:
%-15s
means left justify a 15-space field for a string. Here's the output:对我来说比循环表达式更清晰
for me is even clearer than expression with loop
"%10s" % obj
将确保至少 10 个空格,并且 obj 的字符串表示形式右对齐。"%-10s" % obj
执行相同操作,但左对齐。"%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.