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

Python实现带间隔范围的星号图案打印并显示星数标注

解决星号图案添加数量标注的问题

嘿,这个小需求很容易实现!你只需要调整print语句的内容,把星号的数量动态添加到输出里就行。

修改后的代码

lower = int(input("what is the minimum number of stars: "))
upper = int(input("what is the maximum number of stars: "))
interval = int(input("enter the interval:"))
for i in range(lower, upper + 1, interval):
    # 用f-string把星号数量拼接在星号后面
    print((lower) * ' ' + i * '*' + f'({i} stars)')

改动说明

原来的代码只输出了缩进空格和星号,现在我们在print里追加了格式化字符串:

  • f'({i} stars)'会自动把当前循环的星号数量i转换成字符串,和( stars)组合成标注文本
  • 如果你习惯用字符串拼接的方式,也可以写成:'(' + str(i) + ' stars)',效果完全一致

示例运行效果

假设输入lower=3、upper=11、interval=4,输出会是:

*** (3 stars)
   ******* (7 stars)
   *********** (11 stars)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:31:43