使用制表符而不是空格进行打印

5

假设我想要这样打印:

print 1,"hello", 2, "fart"

在Python 2中,使用制表符而不是空格的最Pythonic方法是什么?

这是一个非常愚蠢的问题,但我似乎找不到答案!

3个回答

7
另一种方法是展望未来!
# Available since Python 2.6
from __future__ import print_function

# Now you can use Python 3's print
print(1, 'hello', 2, 'fart', sep='\t')

在大多数情况下,这可能是更好的方法。我不删除我的答案的原因是因为这个“__future__”导入在所有Python 2版本中都不可用。 - Markus Unterwaditzer
@MarkusUnterwaditzer:确实,如果我没记错的话,它只在Python 2.6及以上版本可用。 - voithos

3
使用 str.join 方法:
print '\t'.join(map(str, (1, "hello", 2, "fart")))

我尝试过了!我得到的是:Traceback (most recent call last): File "<pyshell#148>", line 1, in <module> print '\t'.join((1, "hello", 2, "fart"))d TypeError: sequence item 0: expected string, int found - eye_mew
抱歉,我完全忽略了这一点。根据我上面的代码,每个参数都需要是一个字符串。我更新了我的代码,将所有内容转换为字符串。 - Markus Unterwaditzer

0
我会使用生成器表达式,例如:
print '\t'.join((str(i) for i in (1, "hello", 2, "fart")))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接