我的代码如下:
import sys
print "What are his odds of hitting?", ( 25.0 / 10.0 ) * 8 + 65, sys.stdout.write('%')
当我在Powershell(Windows7)中运行它时,我会得到这个:
What are his odds of hitting? 85.0%None
我想得到的是:
What are his odds of hitting? 85.0%
为什么我最后会得到"无"?我该如何阻止这种情况的发生?
您正在打印sys.stdout.write()
调用的返回值:
print "What are his odds of hitting?", ( 25.0 / 10.0 ) * 8 + 65, sys.stdout.write('%')
该函数返回None
。函数也写入与print
相同的文件描述符,因此首先将%
写入stdout,然后要求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()
方法,该语言的新添加)
sys.stdout.write('%')
返回None
。它只是打印消息,不返回任何内容。
只需将"%"
放在末尾,而不是调用sys.stdout.write
或者,您可以在此处使用.format()
:
print "What are his odds of hitting? {}%".format(( 25.0 / 10.0 ) * 8 + 65)