Python:使用print命令避免换行 [英] Python: avoid new line with print command

查看:96
本文介绍了Python:使用print命令避免换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天开始编程,并在Python中遇到此问题.这真是愚蠢,但我不知道该怎么做.当我使用print命令时,它将打印我想要的任何内容,然后转到另一行.例如:

I'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"

应返回:

这应该在同一行

this should be on the same line

但返回:

这应该是
在同一行

this should be
on the same line

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

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

但是它不能将最后一个(x)识别为输入的值,而是精确打印:(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)

例如我输入test2(3)会给出:

不是,不是两个,而是一个
3

Nope, that is not a two, that is a
3

因此,要么我需要让Python将打印行内的(x)识别为数字,要么;或在同一行上打印两个不同的东西. 在此先感谢您,并对如此愚蠢的问题表示歉意.

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.

重要提示:我正在使用版本2.5.4

另一注:如果我在第二张纸上放print "Thing" , print "Thing2",它说语法错误".

Another note: If i put print "Thing" , print "Thing2" it says "Syntax error" on the 2nd print.

推荐答案

Python 3.x 中,可以对print()函数使用end自变量来防止换行符正在打印:

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="")

Python 2.x 中,您可以使用结尾逗号:

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", x

请注意,末尾的逗号仍会导致在行尾打印一个空格,即等同于在Python 3中使用end=" ".要抑制空格字符,您也可以使用

Note 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_function

可以访问Python 3打印功能或使用sys.stdout.write().

to get access to the Python 3 print function or use sys.stdout.write().

这篇关于Python:使用print命令避免换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆