python - 我试图制作一个乘法表
问题描述
我正在尝试打印一个看起来像这样没有额外空格的表格,并且用户输入了下限(在此示例 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
解决方案
您应该使用格式字符串和 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
推荐阅读
- javascript - req.params 返回未定义(它实际上将 :itemId 作为字符串返回,所以它有点未定义)而不是 id
- python - 检测/识别如何工作(Python)?
- java - 有没有办法在返回结果集时有条件地忽略某个 JPA 实体列
- javascript - 路由''配置无效:redirectTo和children不能一起使用
- reactjs - 反应;在 UseState 中设置默认日期范围值,并确保获取设置值并且之前未分配
- jboss - 是否有任何工具可以监控 jboss 重启后部署了哪些 .war 文件?
- java - 使用 antlr 4 的循环
- c# - 使用 RawPrinterHelper 打印其他语言字符而不是英语
- firebase - Firestore 中的无限循环
- amazon-web-services - 如何将参数传递给 Map 任务中的所有内部工作流任务?