String formatting in Python version earlier than 2.6

前端 未结 5 760

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

提交回复
热议问题