连接 \t 在 Python 中导致不规则间距
w.write(str(entries[0]) + "\t" + (str(entries[1])) + "\n")
这段代码的输出结果是:
Zygophyseter 1
Zygorhiza 1
Zygospore 1
Zygote_(band) 1
Zygote_intrafallopian_transfer 1
Zygotes 1
Zygovisti 1
为什么在不同的行中,名字和数字1之间的间距这么不规则呢?
1 个回答
5
你可能误解了制表符的意思。制表符的作用是:从当前位置移动到下一个制表位。
这些制表位的位置取决于你使用的文本编辑器或终端。通常情况下,制表位会设置在每第8列,但在Stack Overflow上,它们设置在第四列:
>>> def show_tabs():
... print('\t'.join(['v'] * 8))
... for i in range(1, 33):
... print(''.join(map(lambda j: str(j)[-1], range(1, i))), 'tab to here', sep='\t')
...
>>> show_tabs()
v v v v v v v v
tab to here
1 tab to here
12 tab to here
123 tab to here
1234 tab to here
12345 tab to here
123456 tab to here
1234567 tab to here
12345678 tab to here
123456789 tab to here
1234567890 tab to here
12345678901 tab to here
123456789012 tab to here
1234567890123 tab to here
12345678901234 tab to here
123456789012345 tab to here
1234567890123456 tab to here
12345678901234567 tab to here
123456789012345678 tab to here
1234567890123456789 tab to here
12345678901234567890 tab to here
123456789012345678901 tab to here
1234567890123456789012 tab to here
12345678901234567890123 tab to here
123456789012345678901234 tab to here
1234567890123456789012345 tab to here
12345678901234567890123456 tab to here
123456789012345678901234567 tab to here
1234567890123456789012345678 tab to here
12345678901234567890123456789 tab to here
123456789012345678901234567890 tab to here
1234567890123456789012345678901 tab to here
在你自己的终端运行上面的代码,就能很快看到你的制表设置是什么。
在你的文本中,有一行的字符数少于8个,所以下一个制表位就在从开始算起的第8个字符位置。有一行的字符数超过16个,所以下一个制表位在第24个字符位置。大多数行的字符数在9到14个之间,因此下一个制表位在第16个字符位置。换句话说,你的输出与在列之间使用制表符是完全一致的。
如果你想要输出的文本能完美对齐,你可以调整制表符以适应特定的制表位配置(根据第一列的长度使用更多或更少的制表符),或者只使用空格,并再次调整间距。Python可以帮助你实现后者,具体可以参考使用str.format()
进行格式化,你可以在给定的空白宽度内左对齐或右对齐文本。