Python:避免使用print命令换行

时间:2012-06-29 17:09:35

标签: python printing newline python-2.5

我今天开始编程并且在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"放在第二次打印时显示“语法错误”。

5 个答案:

答案 0 :(得分:175)

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()

答案 1 :(得分:117)

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() function中,您可以说

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的参数,您可以使用Python 3.x进行打印,以控制相邻字符串的分隔方式(或不依赖于分配给sep的值)

,例如,

Python 2.x

print 'hi', 'there'

给出

hi there

Python 3.x

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

给出

hithere

答案 2 :(得分:23)

如果您使用的是Python 2.5,则无法使用,但对于使用2.6或2.7的用户,请尝试

from __future__ import print_function

print("abcd", end='')
print("efg")

结果

abcdefg

对于使用3.x的用户,这已经是内置的。

答案 3 :(得分:10)

你只需要这样做:

print 'lakjdfljsdf', # trailing comma

然而在:

print 'lkajdlfjasd', 'ljkadfljasf'

有隐含的空白(即' ')。

您还可以选择:

import sys
sys.stdout.write('some data here without a new line')

答案 4 :(得分:5)

使用尾随逗号来阻止显示新行:

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

您可以使用%运算符(模数)访问有关字符串格式的其他documentation