我今天开始编程,在使用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将打印行中的my (x)识别为数字;要么在同一行打印两个不同的东西。提前感谢并为这么愚蠢的问题道歉。
重要说明:我正在使用版本2.5.4
另一个注意:如果我把print "Thing" , print "Thing2"
放在第二个打印上,它会显示“语法错误”。
发布于 2012-06-30 01:10:44
在Python3.x中,您可以使用print()
函数的end
参数来防止打印换行符:
print("Nope, that is not a two. That is a", end="")
在Python2.x中,您可以使用尾随逗号:
print "this should be",
print "on the same line"
不过,您不需要使用此命令来简单地打印变量:
print "Nope, that is not a two. That is a", x
请注意,尾随逗号仍然会导致在行尾打印一个空格,也就是说,它等同于在Python3中使用end=" "
。
from __future__ import print_function
要访问Python3print函数或使用sys.stdout.write()
。
发布于 2012-06-30 01:18:05
在Python2.x中,只需在print
语句的末尾添加一个,
即可。如果您希望避免print
在项目之间放置的空格,请使用sys.stdout.write
。
import sys
sys.stdout.write('hi there')
sys.stdout.write('Bob here.')
收益率:
hi thereBob here.
请注意,两个字符串之间没有换行符或空格。
在带有print() function的Python3.x中,您可以这样说
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
的参数,您可以使用Python3.x在打印中设置该参数,以控制如何分隔相邻的字符串(或者不设置,具体取决于分配给sep
的值)
例如,
Python 2.x
print 'hi', 'there'
给出
hi there
Python 3.x
print('hi', 'there', sep='')
给出
hithere
发布于 2012-06-30 01:18:08
如果您使用的是Python 2.5,这将不起作用,但对于使用2.6或2.7的用户,请尝试
from __future__ import print_function
print("abcd", end='')
print("efg")
结果:
abcdefg
对于那些使用3.x的用户,这已经是内置的了。
https://stackoverflow.com/questions/11266068
复制相似问题