我今天开始编程,在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)",就会得到。
不,这不是一个2,这是一个 3
所以,要么我需要让Python将打印行内的(x)识别为数字;要么打印两个不同的东西,但在同一行。 提前感谢,并为这样一个愚蠢的问题感到抱歉。
重要的说明。我使用的是版2.5.4。
另一个问题:如果我把 "print "Thing",print "Thing2"",它在第二次打印时显示"语法错误" 。
在Python 3.x中,你可以使用print()
函数的end
参数来防止打印换行符。
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()
。
利用尾部的逗号来防止呈现新的一行。
print "this should be"; print "on the same line"
应该是。
print "this should be", "on the same line"
此外,你可以通过以下方式将被传递的变量附加到所需字符串的末尾。
print "Nope, that is not a two. That is a", x
你也可以使用。
print "Nope, that is not a two. That is a %d" % x #assuming x is always an int
您可以访问有关利用%
运算符(modulo)进行字符串格式化的其他文档。