首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python:使用print命令避免换行

Python:使用print命令避免换行
EN

Stack Overflow用户
提问于 2012-06-30 01:09:35
回答 5查看 447.1K关注 0票数 143

我今天开始编程,在使用Python时遇到了这个问题。这是相当愚蠢的,但我不知道怎么做。当我使用print命令时,它会打印我想要的任何内容,然后转到不同的行。例如:

代码语言:javascript
复制
print "this should be"; print "on the same line"

应返回:

这应该在同一行上

而是返回:

这应该是

在同一行上

更准确地说,我试图用if创建一个程序,告诉我一个数字是否为2

代码语言:javascript
复制
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)“(带括号的字母)。为了让它工作,我必须写:

代码语言:javascript
复制
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"放在第二个打印上,它会显示“语法错误”。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2012-06-30 01:10:44

Python3.x中,您可以使用print()函数的end参数来防止打印换行符:

代码语言:javascript
复制
print("Nope, that is not a two. That is a", end="")

Python2.x中,您可以使用尾随逗号:

代码语言:javascript
复制
print "this should be",
print "on the same line"

不过,您不需要使用此命令来简单地打印变量:

代码语言:javascript
复制
print "Nope, that is not a two. That is a", x

请注意,尾随逗号仍然会导致在行尾打印一个空格,也就是说,它等同于在Python3中使用end=" "

代码语言:javascript
复制
from __future__ import print_function

要访问Python3print函数或使用sys.stdout.write()

票数 194
EN

Stack Overflow用户

发布于 2012-06-30 01:18:05

Python2.x中,只需在print语句的末尾添加一个,即可。如果您希望避免print在项目之间放置的空格,请使用sys.stdout.write

代码语言:javascript
复制
import sys

sys.stdout.write('hi there')
sys.stdout.write('Bob here.')

收益率:

代码语言:javascript
复制
hi thereBob here.

请注意,两个字符串之间没有换行符或空格。

在带有print() functionPython3.x中,您可以这样说

代码语言:javascript
复制
print('this is a string', end="")
print(' and this is on the same line')

并获取:

代码语言:javascript
复制
this is a string and this is on the same line

还有一个名为sep的参数,您可以使用Python3.x在打印中设置该参数,以控制如何分隔相邻的字符串(或者不设置,具体取决于分配给sep的值)

例如,

Python 2.x

代码语言:javascript
复制
print 'hi', 'there'

给出

代码语言:javascript
复制
hi there

Python 3.x

代码语言:javascript
复制
print('hi', 'there', sep='')

给出

代码语言:javascript
复制
hithere
票数 121
EN

Stack Overflow用户

发布于 2012-06-30 01:18:08

如果您使用的是Python 2.5,这将不起作用,但对于使用2.6或2.7的用户,请尝试

代码语言:javascript
复制
from __future__ import print_function

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

结果:

代码语言:javascript
复制
abcdefg

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

票数 24
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11266068

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档