You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python生成自定义上下界乘法表消除多余缩进问题求解

Python自定义上下界无多余空格乘法表实现

问题原因

现有代码输出的多余缩进来自于拼接乘积时使用的\t制表符,制表符在不同输出环境下会自动对齐为4/8个空格长度,不符合单空格分隔的预期,同时循环逐次拼接分隔符会导致每一行末尾多一个多余的空白符。

修正代码

逐行打印版本(推荐,内存占用更低)

# 获取上下界输入
lower_bound = int(float(input("Give me the lower bound: ")))
upper_bound = int(float(input("Give me the upper bound: ")))

for i in range(lower_bound, upper_bound + 1):
    # 生成当前行所有乘积的字符串序列,用单空格拼接
    products = ' '.join(str(i * x) for x in range(lower_bound, upper_bound + 1))
    # 拼接行前缀后打印
    print(f"{i}: {products}\n")

保留原字符串拼接逻辑版本

# 获取上下界输入
input3 = int(float(input("Give me the lower bound: ")))
input4 = int(float(input("Give me the upper bound: ")))
multiplication_table_str = ""

for i in range(input3, input4 + 1):
    multiplication_table_str += str(i) + ": "
    # 收集当前行所有乘积的字符串
    product_list = []
    for x in range(input3, input4 + 1):
        product_list.append(str(i * x))
    # 用单空格拼接后追加换行
    multiplication_table_str += ' '.join(product_list) + "\n\n"    

print(multiplication_table_str)

核心修改说明

  • 替换\t制表符为单空格作为数值分隔符,避免制表符自带的对齐缩进
  • 使用str.join()方法拼接同一行的乘积字符串,自动避免末尾多余分隔符
  • 新增双换行符\n\n实现预期效果里行与行之间的空行间隔

内容的提问来源于stack exchange,提问作者Mo yo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 02:09:01