Python: avoid new line with print command
我今天已经开始编程了,关于python有这个问题。这很愚蠢,但我不知道怎么做。当我使用print命令时,它打印我想要的任何内容,然后转到另一行。例如:
| 1 | print"this should be"; print"on the same line" | 
应该返回:
this should be on the same line
但相反,返回:
this should be
on the same line
更准确地说,我试图用
| 1 2 3 4 5 | 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)" | 
但它没有将最后一个
| 1 | print"Nope, that is not a two. That is a"; print (x) | 
如果我进入
Nope, that is not a two, that is a
3
因此,要么我需要让python将打印行中的(x)识别为数字,要么打印两个不同的东西,但在同一行上。事先谢谢你,对这样一个愚蠢的问题深表歉意。
重要提示:我使用的是2.5.4版
另一个注意事项:如果我把
在python 3.x中,可以使用
| 1 | print("Nope, that is not a two. That is a", end="") | 
在python 2.x中,可以使用尾随逗号:
| 1 2 | print"this should be", print"on the same line" | 
您不需要这样简单地打印一个变量,但是:
| 1 | print"Nope, that is not a two. That is a", x | 
请注意,尾随逗号仍会导致行尾打印一个空格,即相当于在python 3中使用
| 1 | from __future__ import print_function | 
要访问python 3打印功能或使用
在python 2.x中,只需将
| 1 2 3 4 | import sys sys.stdout.write('hi there') sys.stdout.write('Bob here.') | 
产量:
| 1 | hi thereBob here. | 
注意,两个字符串之间没有换行符或空格。
在python 3.x中,通过print()函数,您可以说
| 1 2 | print('this is a string', end="") print(' and this is on the same line') | 
得到:
| 1 | this is a string and this is on the same line | 
还有一个名为
例如。,
Python 2 x
| 1 | print 'hi', 'there' | 
给予
| 1 | hi there | 
Python 3 x
| 1 | print('hi', 'there', sep='') | 
给予
| 1 | hithere | 
如果您使用的是python 2.5,这将不起作用,但是对于使用2.6或2.7的人,请尝试
| 1 2 3 4 | from __future__ import print_function print("abcd", end='') print("efg") | 
结果在
| 1 | abcdefg | 
对于那些使用3.x的用户,这已经是内置的了。
您只需执行以下操作:
| 1 | print 'lakjdfljsdf', # trailing comma | 
然而,在:
| 1 | print 'lkajdlfjasd', 'ljkadfljasf' | 
有隐含的空白(即
您还可以选择:
| 1 2 | import sys sys.stdout.write('some data here without a new line') | 
使用尾随逗号防止出现新行:
| 1 | print"this should be"; print"on the same line" | 
应该是:
| 1 | print"this should be","on the same line" | 
此外,您可以通过以下方式将要传递的变量附加到所需字符串的末尾:
| 1 | print"Nope, that is not a two. That is a", x | 
您还可以使用:
| 1 | print"Nope, that is not a two. That is a %d" % x #assuming x is always an int | 
您可以使用