这个问题已经在这里有一个答案:
如何打印没有换行符或空格? 26答案我今天开始编程,并在Python中遇到这个问题。 这很笨,但我不知道该怎么做。 当我使用打印命令时,它会打印任何我想要的,然后转到另一行。 例如:
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"它在第二个打印中显示“Syntax error”。
This question already has an answer here:
How to print without newline or space? 21 answersI've started programming today and have this issue with Python. It's pretty dumb but I can't figure out how to do it. When I use the print command, it prints whatever I want and then goes to a different line. For example:
print "this should be"; print "on the same line"Should return:
this should be on the same line
but instead returns:
this should be on the same line
More precisely I was trying to create a program with if that told me whether a number was a 2 or not
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)"But it doesn't recognise the last (x) as the value entered, and rather prints exactly: "(x)" (the letter with the brackets). To make it work I have to write:
print "Nope, that is not a two. That is a"; print (x)And if e.g. I enter test2(3) that gives:
Nope, that is not a two, that is a 3
So either i need to make Python recognise my (x) inside a print line as the number; or to print two separate things but on the same line. Thanks in advance and sorry for such a stupid question.
IMPORTANT NOTE: I am using version 2.5.4
Another note: If i put print "Thing" , print "Thing2" it says "Syntax error" on the 2nd print.
最满意答案
您可以使用后缀逗号来避免打印换行符:
print "this should be", print "on the same line"你不需要这样来简单地打印一个变量:
print "Nope, that is not a two. That is a", x注意:从Python 3.x及以上版本
print("Nope, that is not a two. That is a", x)In Python 3.x, you can use the end argument to the print() function to prevent a newline character from being printed:
print("Nope, that is not a two. That is a", end="")In Python 2.x, you can use a trailing comma:
print "this should be", print "on the same line"You don't need this to simply print a variable, though:
print "Nope, that is not a two. That is a", xNote that the trailing comma still results in a space being printed at the end of the line, i.e. it's equivalent to using end=" " in Python 3. To suppress the space character as well, you can either use
from __future__ import print_functionto get access to the Python 3 print function or use sys.stdout.write().
更多推荐
发布评论