views:

3321

answers:

6

I am using Python 2.5.2

>>> for x in range(1,11):
print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)

Traceback (most recent call last): File "", line 2, in print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) AttributeError: 'str' object has no attribute 'format'

I am not getting the problem

When i did dir('hello') there was no format attribute.

How can i solve this ?

A: 

I get no error while executing this. double check.

attwad
+3  A: 

Which Python version do you use?

Edit For Python 2.5, use "x = %s" % (x) (for printing strings)

If you want to print other types, see here.

Loïc Wolff
Python 2.5.2...
str.format() only works in 2.6+ and py3k
Loïc Wolff
+4  A: 

I believe that is a Python 3.0 feature, although it is in version 2.6. But if you have a version of Python below that, that type of string formatting will not work.

If you are trying to print formatted strings in general, use Python's printf-style syntax through the % operator. For example:

print '%.2f' % some_var
htw
+15  A: 

format method was introduced in python 3.0 and backported only to 2.6

SilentGhost
Well, it not the answer for the asked question. Totally nothing about the solution.
Nikolay Vyahhi
wtf? his problem is that he's using method that is not supported. he can stop doing that and the problem will go away.
SilentGhost
why the downvote?
SilentGhost
+6  A: 

For Python versions below 2.6, use the % operator.

You should also be aware that this operator can interpolate by name from a mapping, instead of just positional arguments:

>>> "%(foo)s %(bar)d" % {'bar': 42, 'foo': "spam", 'baz': None}
'spam 42'

In combination with the fact that the built-in vars() function returns attributes of a namespace as a mapping, this can be very handy:

>>> bar = 42
>>> foo = "spam"
>>> baz = None
>>> "%(foo)s %(bar)d" % vars()
'spam 42'
bignose
This is a good description, but it doesn't describe how to implement the formatting in the presented example.
Jason R. Coombs
+1  A: 

Although the existing answers describe the causes and point in the direction of a fix, none of them actually provide a solution that accomplishes what the question asks.

You have two options to solve the problem. The first is to upgrade to Python 2.6 or greater, which supports the format string construct.

The second option is to use the older string formatting with the % operator. The equivalent code of what you've presented would be as follows.

for x in range(1,11):
  print '%2d %3d %4d' % (x, x*x, x*x*x)

This code snipped produces exactly the same output in Python 2.5 as your example code produces in Python 2.6 and greater.

Jason R. Coombs