Python:避免使用打印命令换行

新手上路,请多包涵

当我使用 print 命令时,它会打印我想要的任何内容,然后转到另一行。例如:

 print "this should be"; print "on the same line"

应该返回:

这应该在同一行

而是返回:

这应该是

在同一条线上

更准确地说,我试图用 if 创建一个程序,它告诉我一个数字是否是 2

 def test2(x):
    if x == 2:
        print "Yeah bro, that's tottaly a two"
    else:
        print "Nope, that is not a two. That is a (x)"

但它无法识别最后一个 (x) 作为输入的值,而是准确打印:“(x)”(带括号的字母)。为了让它工作,我必须写:

 print "Nope, that is not a two. That is a"; print (x)

如果我输入 test2(3) 给出:

不,那不是二,那是一

3个

因此,要么我需要让 Python 将打印行中的 (x) 识别为数字;或者在同一行打印两个不同的东西。

重要说明:我使用的是 2.5.4 版

另一个注意事项:如果我输入 print "Thing" , print "Thing2" 它会在第二次打印时显示“语法错误”。

原文由 Javicobos 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 253
2 个回答

Python 3.x 中,您可以使用 end 参数到 print() 函数来防止打印换行符:

 print("Nope, that is not a two. That is a", end="")

Python 2.x 中,您可以使用尾随逗号:

 print "this should be",
print "on the same line"

但是,您不需要它来简单地打印一个变量:

 print "Nope, that is not a two. That is a", x

请注意,尾随逗号仍然会导致在行尾打印一个空格,即它等效于在 Python 3 中使用 end=" " 。要同时抑制空格字符,您可以使用

from __future__ import print_function

访问 Python 3 打印功能或使用 sys.stdout.write()

原文由 Sven Marnach 发布,翻译遵循 CC BY-SA 3.0 许可协议

Python 2.x 中,只需将 , 放在 print 语句的末尾。如果要避免 print 在项目之间放置的空格,请使用 sys.stdout.write

 import sys

sys.stdout.write('hi there')
sys.stdout.write('Bob here.')

产量:

 hi thereBob here.

请注意,两个字符串之间 没有换行符 或 _空格_。

Python 3.x 中,凭借其 print() 函数,您可以说

print('this is a string', end="")
print(' and this is on the same line')

并得到:

 this is a string and this is on the same line

还有一个名为 sep 的参数,您可以在 print 中使用 Python 3.x 设置该参数以控制相邻字符串的分隔方式(或不分隔取决于分配给 sep 的值)

例如,

Python 2.x

 print 'hi', 'there'

hi there

Python 3.x

 print('hi', 'there', sep='')

hithere

原文由 Levon 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题