使用sys.stdout.write时,在我写完之后会出现“None”

时间:2013-07-29 07:18:37

标签: python python-2.7

我的代码如下所示:

import sys
print "What are his odds of hitting?", ( 25.0 / 10.0 ) * 8 + 65, sys.stdout.write('%')

当我在Powershell(Windows 7)中运行它时,我得到了这个:

What are his odds of hitting? 85.0%None

我想得到的是:

What are his odds of hitting? 85.0%

为什么我在结尾处得到“无”?我该如何阻止这种情况发生?

2 个答案:

答案 0 :(得分:3)

您正在打印sys.stdout.write()来电的返回值

print "What are his odds of hitting?", ( 25.0 / 10.0 ) * 8 + 65, sys.stdout.write('%')

该函数返回None。函数写入与print相同的文件描述符,因此您首先%写入stdout,然后询问{{1}将更多文字写入print,包括返回值stdout

你可能只想在那里添加None而没有空格。使用字符串连接或格式化:

%

print "What are his odds of hitting?", str(( 25.0 / 10.0 ) * 8 + 65) + '%'

print "What are his odds of hitting? %.02f%%" % (( 25.0 / 10.0 ) * 8 + 65)

两个字符串格式化变体格式化浮点值,小数点后面有两位小数。请参阅String formatting operations(针对print "What are his odds of hitting? {:.02f}%".format((25.0 / 10.0 ) * 8 + 65) 变体,旧样式字符串格式设置)或Format String Syntax(针对str.format() method,语言的新增内容)

答案 1 :(得分:1)

sys.stdout.write('%')返回None。它只是打印消息而不返回任何内容。

只需将"%"放在最后,而不是调用sys.stdout.write

或者,您可以在此处使用.format()

print "What are his odds of hitting? {}%".format(( 25.0 / 10.0 ) * 8 + 65)