首页 > 解决方案 > 我试图制作一个乘法表

问题描述

我正在尝试打印一个看起来像这样没有额外空格的表格,并且用户输入了下限(在此示例 4 中)和上限(在此示例 8 中)。

#Get the inputs
input3=int(float(input("Give me the lower bound: ")))
input4=int(float(input("Give me the upper bound: ")))
#create a loop to multiply the upper and lower bounds 
multiplication_table_str= ""

for i in range(input3,input4+1):
    multiplication_table_str+= str(i) + ": "
    for x in range(input3,input4+1):
        multiplication_table_str+=str(i*x)+"\t"
    multiplication_table_str+="\n"    

print(multiplication_table_str)

我所拥有的输出正确,但数字内部有一个额外的缩进,我想摆脱它,我不知道如何。我希望它看起来像这样:

4: 16 20 24 28 32

5: 20 25 30 35 40

6: 24 30 36 42 48

7: 28 35 42 49 56

8: 32 40 48 56 64

标签: pythoncoding-style

解决方案


您应该使用格式字符串和 join() 函数来构建您的字符串。这将使您完全控制间距和数字对齐:

#Get the inputs
low=int(float(input("Give me the lower bound: ")))
high=int(float(input("Give me the upper bound: ")))

rWidth = len(str(high))
mTable = "\n".join( f"{r:{rWidth}}: "
                    + " ".join(f"{r*c:{len(str(c*high))}}"
                               for c in range(low,high+1))
                    for r in range(low,high+1))    
print(mTable)

样品运行:

Give me the lower bound: 4
Give me the upper bound: 8
4: 16 20 24 28 32
5: 20 25 30 35 40
6: 24 30 36 42 48
7: 28 35 42 49 56
8: 32 40 48 56 64

Give me the lower bound: 8
Give me the upper bound: 11
 8: 64 72  80  88
 9: 72 81  90  99
10: 80 90 100 110
11: 88 99 110 121

推荐阅读