2

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?

1
  • 1
    What python version are you using? Commented Aug 15, 2010 at 14:47

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

This is also supported Python 2.7 What’s New in Python 2.7 — Python v2.7 documentation docs.python.org/whatsnew/2.7.html#other-language-changes
1

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.

Comments

-1

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'

4 Comments

OP is asking about advanced string formatting, not the % interpolation.
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?
Just because someone hasn't posted an answer of their own doesn't mean they can't point out issues with others' answers.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.