使用 space 之间的结果打印到标准输出?
Print to stdout with space's between result?
我遇到了一个小问题,
我想将结果打印到标准输出,结果之间有空格
x y
我的代码打印它 (x, y)
因为我只在它们之间用逗号返回它们
return x, y
在打印 x 和 y 之前我必须添加什么?
您刚刚打印了 python tuple
:
>>> print((x, y))
(x, y)
您可以unpack
得到您想要的结果:
>>> print(*(x, y))
x y
要在 python 2.x 中使用,请执行 from __future__ import print_function
你的函数returns一个元组。你看到的是元组的标准表示。
有不同的解决方案;
1) 赋值给两个变量并打印:
x, y = function()
print x, y # in Python 3 use print(x, y)
2) 在python3中你可以解压:
res = function()
print(*res)
3) 您可以使用 format
:
res = function()
print '{} {}'.format(res[0], res[1])
# In python 3 also with unpacking; print('{} {}'.format(*res))
请注意,使用 format
可能会给您最大的灵活性 w.r.t。输出看起来如何。例如,如果值是浮点数。 Python 3 中的示例:
>>> res = (12/7, 7/3)
>>> res
(1.7142857142857142, 2.3333333333333335)
>>> print(*res)
1.7142857142857142 2.3333333333333335
>>> print('{:.3f} {:.3f}'.format(*res))
1.714 2.333
我遇到了一个小问题, 我想将结果打印到标准输出,结果之间有空格
x y
我的代码打印它 (x, y)
因为我只在它们之间用逗号返回它们
return x, y
在打印 x 和 y 之前我必须添加什么?
您刚刚打印了 python tuple
:
>>> print((x, y))
(x, y)
您可以unpack
得到您想要的结果:
>>> print(*(x, y))
x y
要在 python 2.x 中使用,请执行 from __future__ import print_function
你的函数returns一个元组。你看到的是元组的标准表示。
有不同的解决方案;
1) 赋值给两个变量并打印:
x, y = function()
print x, y # in Python 3 use print(x, y)
2) 在python3中你可以解压:
res = function()
print(*res)
3) 您可以使用 format
:
res = function()
print '{} {}'.format(res[0], res[1])
# In python 3 also with unpacking; print('{} {}'.format(*res))
请注意,使用 format
可能会给您最大的灵活性 w.r.t。输出看起来如何。例如,如果值是浮点数。 Python 3 中的示例:
>>> res = (12/7, 7/3)
>>> res
(1.7142857142857142, 2.3333333333333335)
>>> print(*res)
1.7142857142857142 2.3333333333333335
>>> print('{:.3f} {:.3f}'.format(*res))
1.714 2.333