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"

Should return:

this should be on the same line

but instead returns:

this should be

on the same line

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

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)

And if e.g. I enter test2(3) that gives:

Nope, that is not a two, that is a

3

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.

IMPORTANT NOTE: I am using version 2.5.4

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

解决方案

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

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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值