String formatting in Python version earlier than 2.6

前端 未结 5 754

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:

5条回答
  •  一生所求
    2020-12-16 10:08

    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.

提交回复
热议问题