python - 居中矩阵

标签 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 |
        +-----------+

最佳答案

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

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

关于python - 居中矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11497485/

相关文章:

python - 存储上传的照片和文档 - 文件系统与数据库 blob

c# - ByteArray 的 String.Format 将 0x00 转换为 0,如何保留 00

python - wx.ListBox 中的字符串格式化

c# 文本框数据与日期格式绑定(bind)

json - golang 格式数据一次性转换为 JSON 格式

python - 我必须递归检查集合Python3.0中是否存在该值

python - 获取 numpy 数组每行中第一个零的索引数组

python - 如何检查文件夹是否是任何连接点的目标?

python - 如何在字符串中添加 X 个空格

python - 在 Python 中修改格式化数字中的前导字符?