2017-03-29 85 views
2

我已经写了如下的Python代码:打印输出没有显示正确的格式

magicNumber = 25 

for n in range(100): 
    if n is magicNumber: 
     print(n, " is the magic number") 
     break 
    else: 
     print(n) 

输出的最后一行的格式如下面显示:

(25, ' is the magic number') 

请让我知道我能做些什么,以具有的last lineoutput为:

25 is the magic number 
+0

你使用python 2不3 – abccd

+1

如果[R使用python 2删除括号()。 – shiva

回答

3

有很多方法你可以做到这一点,因为你使用python 2,不存在一个默认的打印功能。所以你将不得不导入它,一种方法是将其添加到代码的顶部。

from __future__ import print_function 

其它方法包括使用字符串格式化,如:

print "%s is the magic number" % n 

而且

print "{0} is the magic number".format(n) 

或者,你可以很容易地取出支架,它都将是相同的。

print n, "is the magic number" 
1

您正在运行python 2中的代码。这解释了正在打印的大括号。在python 3中运行它会按照您的预期工作。或者,如果你还是喜欢蟒蛇2,则只是删除括号,并把

print n,' is the magicnumber' 
1

为Python 2.x的 - 打印作为一个命令 只是删除括号,并预期它会奏效。

print n, " is the magic number"

为Python 3.x的 - 打印充当功能;所以下面很好。

print(n, " is the magic number")

还有一些其他的方法,也可以由用户abccd的建议。