python:打印的逗号为“\ t”

时间:2012-11-17 17:41:18

标签: python

打印中的,添加了空格

>>> print "a","b"
a b

如果我需要\t,我会把

>>> print "a","\t","b"
a       b

如何将,的输出更改为\t

4 个答案:

答案 0 :(得分:6)

您可以从print()导入__future__函数并使用sep='\t',在python 3中引入了print()函数,它替换了所使用的print语句在python 2.x中:

In [1]: from __future__ import print_function

In [2]: print('a','b',sep='\t')
a   b

print()上的帮助:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep:  string inserted between values, default a space.
end:  string appended after the last value, default a newline.

答案 1 :(得分:5)

改为使用str.join()

print '\t'.join(('a', 'b'))

python print语句将表达式中的任何元素转换为字符串并使用空格将它们连接起来;如果你想使用不同的分隔符,你必须手动加入。

或者,使用print() function,这是为了方便过渡到Python 3而引入的:

from __future__ import print_function
print('a','b',sep='\t')

print()函数接受sep参数来更改用于分隔值的字符串。在python 3中,只保留print()函数,并删除了python 2中的旧print语句。

答案 2 :(得分:1)

最简单的方法

print("%s\t%s",%(a,b))

答案 3 :(得分:0)