String formatting in Python version earlier than 2.6

前端 未结 5 753

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:00

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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-16 10:10

    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
    
    0 讨论(0)
  • 2020-12-16 10:13

    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.

    0 讨论(0)
  • 2020-12-16 10:15

    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'
    
    0 讨论(0)
提交回复
热议问题