String formatting in Python version earlier than 2.6

血红的双手。 提交于 2019-12-18 03:49:05

问题


When I run the following code in Python 2.5.2:

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

I get:

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

I don't understand the problem.

From dir('hello') there is no format attribute.

How can I solve this?


回答1:


The str.format method was introduced in Python 3.0, and backported to Python 2.6 and later.




回答2:


Your example code seems to be written for Python 2.6 or later, where the str.format method was introduced.

For Python versions below 2.6, use the % operator to interpolate a sequence of values into a format string:

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

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'



回答3:


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



回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/792721/string-formatting-in-python-version-earlier-than-2-6

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!