将矩阵居中

时间:2012-07-16 02:30:43

标签: python string-formatting

我正试图集中这个板,这是代码,我尝试用%* s,但它没有成功。 有什么想法吗?

board = [["1","2","2"],["8*1","2@3","5*6"],["9","5","8"],["2","2","2"],
     ["5*6","6*8","0@2"],["1","2","8"],["1","9","8"],["2*7","7*5","4@2"],["1","3","3"]]

counter = 0

print("--------------+---------------+-------------------")

for row in board:
    counter += 1
    print("|"      "%s"     "|") % ("       |      ".join(row).center(47))
    if counter == 3 or counter == 6 or counter == 9:
        print("---------------+---------------------+--------------")

每个方框的输出应该是这样的

        +-----------+
        | 1 | 1 | 9 |

        |2@3|1*6|7*2|

        | 4 | 1 | 2 |
        +-----------+

3 个答案:

答案 0 :(得分:2)

这就是你想要的,我相信:

board=[["1","2","2"],["8*1","2@3","5*6"],["9","5","8"],["2","2","2"],
["5*6","6*8","0@2"],["1","2","8"],["1","9","8"],["2*7","7*5","4@2"],["1","3","3"]]
counter=0

print ("----------------+---------------+----------------")

for row in board:
        counter+=1
        s="|"
        for column in row:
                s += column.center(15) + "|"
        print(s)
        if counter==3 or counter==6 or counter==9:
                print ("----------------+---------------+----------------")

输出:

----------------+---------------+----------------
|       1       |       2       |       2       |
|      8*1      |      2@3      |      5*6      |
|       9       |       5       |       8       |
----------------+---------------+----------------
|       2       |       2       |       2       |
|      5*6      |      6*8      |      0@2      |
|       1       |       2       |       8       |
----------------+---------------+----------------
|       1       |       9       |       8       |
|      2*7      |      7*5      |      4@2      |
|       1       |       3       |       3       |
----------------+---------------+----------------

答案 1 :(得分:1)

("|"      "%s"     "|")

这是三个字符串文字:"|""%s""|",用空格分隔。 Python将在编译时将它们连接在一起,因为它们是文字(而不是碰巧包含字符串的变量;这种分析不能在编译时完成)。所以整个事情相当于“|%s |”。

如果希望空格包含在字符串中,则在字符串中包含空格:“|%s |”,每边需要任意数量的空格。或者,使用字符串乘法和加法运算来构造字符串:"|" + " " * n + "%s" + " " * n + "|",例如,其中n是每边需要的任意数量的空格。

答案 2 :(得分:1)

我修改了你的代码以产生一些接近你要求的东西:

board = [["1","2","2"],["8*1","2@3","5*6"],["9","5","8"],
         ["2","2","2"],["5*6","6*8","0@2"],["1","2","8"],
         ["1","9","8"],["2*7","7*5","4@2"],["1","3","3"]]

counter = 0

print("+-----------+")

for row in board:
    counter += 1
    print("|%s|" % "|".join(c.center(3) for c in row))
    if counter == 3 or counter == 6 or counter == 9:
        print("+-----------+")

产生:

+-----------+
| 1 | 2 | 2 |
|8*1|2@3|5*6|
| 9 | 5 | 8 |
+-----------+
| 2 | 2 | 2 |
|5*6|6*8|0@2|
| 1 | 2 | 8 |
+-----------+
| 1 | 9 | 8 |
|2*7|7*5|4@2|
| 1 | 3 | 3 |
+-----------+