2013-07-29 27 views
0

我的代碼看起來像這樣經過:當使用sys.stdout.write函數, 「無」 看來我寫的東西

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% 

爲什麼我得到了「無」,在它的結束?我如何阻止這種情況發生?

回答

3

正在打印的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) 

兩個字符串格式化的變化小數點後格式化與兩位小數的浮點值。請參閱String formatting operations(用於'..' % ...變體,舊式字符串格式)或Format String Syntax(用於str.format() method,該語言的新增內容)

1

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

只要把"%"末,而不是調用sys.stdout.write

,或者,你可以在這裏使用.format()

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