格式化乘法表

时间:2019-06-30 00:39:41

标签: python

enter image description here我是python的新手。有人可以建议我如何按照表格中的格式制作表格吗?

格式化说明:

  1. 每个单元格的数字项必须正好是2位数字,如有必要,前导0。

  2. 每个数字单元格正好是4个字符宽,两位数字输入居中。

预先感谢您的帮助!

我已经为乘法逻辑编写了以下代码:

--following code is giving output but I am not able to print it in the format as in the attached picture.

for x in range(1, 10):
        for y in range(1, 10):
            z = x * y
            print(z, end="\t")
        print() #creates the space after the loop

3 个答案:

答案 0 :(得分:1)

这是一个完整的解决方案:

def printMultiplicationTable(size):
    # print the header row
    for x in range(-1, size): # -1 is used as a special value to print the special * character
        print("|", end=" ")
        if x == -1:
            print(" *", end=" ")
        else:
            print("0" + str(x), end=" ")
    print("|")

    # print dashes
    print("-"*(size+1)*5)

    # print the rest of the table
    for x in range(size):
        for y in range(-1, size):
            print("|", end=" ")
            if y == -1: # -1 used as special value for printing out one of the factors of multiplication
                if x == 0:
                    print("00", end=" ")
                else:
                    print("0" * (2 - math.floor(math.log(x, 10) + 1)) + str(x), end=" ")
            else:
                if x * y == 0:
                    print("00", end=" ")
                else:
                    print("0" * (2 - math.floor(math.log(x * y, 10) + 1)) + str(x * y), end=" ")
        print("|")

与x和y的乘积为0的边缘情况有些矛盾,但这使用math.log来计算数字中的位数,并相应地填充空格。

答案 1 :(得分:0)

尝试这个:

for i in range(0, 12):
    print(" " , ("{:02d}".format(i)), " ", "|", end='')
    for j in range(0, 12):
        print(" " , ("{:02d}".format(i*j)), " ", "|", end='')
    print("\n")

答案 2 :(得分:0)

您可以使用漂亮的表http://zetcode.com/python/prettytable/,或者如果格式不完全符合您的需要,则可以自定义自己的表:

#make the definition for each row
def rowTemplate( ):
    return "| " + " | ".join( [ "{:02}" for i in range( 11 ) ]) + " |"

#define the table and header
multiplication_table = []
headers = [ i for i in range( 11 ) ]

#add the row header and separater
multiplication_table.append( rowTemplate().format( *headers ) )
multiplication_table.append( ''.join( ['-' for i in range( len( multiplication_table[0] ))] ))

#add the values and column header
for i in range( 11 ):
    row = [ i ] #add the column header
    for j in range( 11 ):
        row.append( i * j )

    #add the row to the table
    template = rowTemplate()
    multiplication_table.append( template.format( *row ) )

#print results
for row in multiplication_table:
    print( row )