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

发布于 2024-09-18 11:38:57 字数 495 浏览 12 评论 0原文

我有一个看起来像这样的列表列表:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

海拔太高太耀眼 2024-09-25 11:38:57

您需要一个格式字符串:

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

%-15s 表示左对齐字符串的 15 个空格字段。这是输出:

seq1            ACTAGACCCTAG
sequence287653  ACTAGNACTGGG
s9              ACTAGAAACTAG

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
飞烟轻若梦 2024-09-25 11:38:57
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) )

对我来说比循环表达式更清晰

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

兲鉂ぱ嘚淚 2024-09-25 11:38:57

"%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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文