5.24 对齐字符串的两种方法 ========================= .. image:: http://image.iswbm.com/20200804124133.png 第一种:使用 format ------------------- 左对齐 .. code:: python >>> "{:<10}".format("a") 'a ' >>> 右对齐 .. code:: python >>> "{:>10}".format("a") ' a' >>> 居中 .. code:: python >>> "{:^10}".format("a") ' a ' >>> 当你不指定 ``<`` 、\ ``>``\ 、\ ``^`` 时,对字符串,默认左对齐;对数值,默认右对齐 .. code:: python >>> "{:10}".format("a") 'a ' >>> 有了上面的铺垫,写一个整齐的 1-10 的平方、立方表就很容易了。 .. code:: python >>> for x in range(1, 11): ... print('{:2d} {:3d} {:4d}'.format(x, x*x, x*x*x)) ... 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 对齐的思想其实就是在不足的位自动给你补上空格。 如果不想使用空格,可以指定你想要的字符进行填充,比如下面我用 ``0`` 来补全。 .. code:: python >>> for x in range(1, 11): ... print('{:02d} {:03d} {:04d}'.format(x, x*x, x*x*x)) ... 01 001 0001 02 004 0008 03 009 0027 04 016 0064 05 025 0125 06 036 0216 07 049 0343 08 064 0512 09 081 0729 10 100 1000 第二种:使用 ljust, rjust ------------------------- 左对齐 .. code:: python >>> "a".ljust(10) 'a ' >>> 右对齐 .. code:: python >>> "a".rjust(10) ' a' >>> 居中 .. code:: python >>> "a".center(10) ' a ' >>> 同样写一个整齐的 1-10 的平方、立方表 .. code:: python >>> for x in range(1, 11): ... print(' '.join([str(x).ljust(2), str(x * x).ljust(3), str(x * x * x).ljust(4)])) ... 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 如果不想使用空格,而改用 0 来补齐呢?可以这样 .. code:: python >>> for x in range(1, 11): ... print(' '.join([str(x).rjust(2, "0"), str(x*x).rjust(3, "0"), str(x*x*x).rjust(4, "0")])) ... 01 001 0001 02 004 0008 03 009 0027 04 016 0064 05 025 0125 06 036 0216 07 049 0343 08 064 0512 09 081 0729 10 100 1000