0

我的代码如下所示:

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%

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

4

2 回答 2

3

您正在打印调用的返回sys.stdout.write()

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

该函数返回None. 该函数写入相同的文件描述符print,因此您首先写入%标准输出,然后要求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)

或者

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

两种字符串格式变体将浮点值格式化为小数点后两位小数。请参阅字符串格式化操作(对于'..' % ...变体,旧样式字符串格式化)或格式化字符串语法(对于str.format()方法,语言的新添加)

于 2013-07-29T07:21:40.960 回答
1

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

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

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

print "What are his odds of hitting? {}%".format(( 25.0 / 10.0 ) * 8 + 65)
于 2013-07-29T07:19:58.763 回答