views:

71

answers:

3

Hi,

I'm trying to get the following to work in a Python interpreter, however it gives me an error and I cannot seem to find where my mistake is? (I'm a python newbie)

>>> 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'

Any ideas?

A: 

This works:

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

So does this:

>>> print "The value of PI is approx '%f'"  % math.pi
The value of PI is approx '3.141593'
duffymo
OP is asking about advanced string formatting, not the % interpolation.
Wai Yip Tung
OP is asking as a Python noob about a formatting error, which I've corrected. I'm using Python 2.6. Where's your answer, Wai Yip Tung? What have you offered that's better?
duffymo
Just because someone hasn't posted an answer of their own doesn't mean they can't point out issues with others' answers.
Liquid_Fire
That's true; I just disagree with the "issue". Where do you see anything about "advanced string formatting" in the original question? I see someone who was a noob looking for an explanation for a simple error.
duffymo
+3  A: 

You may use Python version < 2.6, version >= 2.6 support {0}, version >= 2.7 support {} format.

shiki
This is also supported Python 2.7What’s New in Python 2.7 — Python v2.7 documentationhttp://docs.python.org/whatsnew/2.7.html#other-language-changes
Wai Yip Tung
Thank you, updated.
shiki
+1  A: 

You're using a too old version of python that does not support this string formatting method. On Python 2.6 this is the result (with a small correction):

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

This method is the new way of string formatting (PEP 3101) and is supposed to replace the old way (with the %). I'm still used to the old way but in the long run I'll probably switch to the new way.

Fabian