小编典典

Python:使用print命令避免换行

python

我今天开始编程,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"在第二张纸上说“语法错误”。


阅读 201

收藏
2020-12-20

共1个答案

小编典典

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

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

from __future__ import print_function

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

2020-12-20