2010-08-15 52 views
2

我試圖獲得以下工作在Python解釋器中,但它給了我一個錯誤,我似乎無法找到我的錯誤在哪裏? (我是一個蟒蛇新手)Python .format - 錯誤

>>> print 'THe value of PI is approx {}.'.format(math.pi) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: 'str' object has no attribute 'format' 

任何想法?

+1

你使用的是什麼python版本? – fabrizioM 2010-08-15 14:47:16

回答

3

您可以使用Python版本< 2.6版本> = 2.6支持{0},版本> = 2.7支持{}格式。

+1

這也支持Python 2.7 Python 2.7的新增功能 - Python v2.7文檔 http://docs.python.org/whatsnew/2.7.html#other-language-changes – 2010-08-15 16:11:20

+0

謝謝,更新。 – 2010-08-16 01:16:19

-1

這工作:

>>> print "The value of PI is approx {'%s'}." % format(math.pi) 
The value of PI is approx {'3.14159265359'}. 

那麼,這是否:

>>> print "The value of PI is approx '%f'" % math.pi 
The value of PI is approx '3.141593' 
+0

OP詢問高級字符串格式,而不是%插值。 – 2010-08-15 16:09:07

+0

OP正在問一個關於格式錯誤的Python小事,我已經更正了。我正在使用Python 2.6。偉業通你的答案在哪裏?你有什麼更好的? – duffymo 2010-08-15 16:19:03

+1

僅僅因爲有人沒有發佈自己的答案並不意味着他們不能指出他人答案的問題。 – 2010-08-15 18:53:47

1

您正在使用不支持此字符串格式設置方法的過時版本的python。在Python 2.6中這是結果(用小校正):

>>> print 'THe value of PI is approx {0}.'.format(math.pi) 
THe value of PI is approx 3.14159265359. 

這種方法的字符串格式化(PEP 3101)的新途徑,應該更換舊的方式(用%)。我仍然習慣了舊的方式,但從長遠來看,我可能會轉向新的方式。