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

Python掷骰子模拟器输出空格问题求助:消除数字与s、冒号间空格

Python掷骰子模拟器输出格式修正问题

我编写的Python掷骰子模拟器输出不符合教授要求,问题在于数字与's'、':'之间存在多余空格,不应出现这些空格。我尝试过strip首尾空格函数、join函数,但均出现错误,希望能获得简单可直接添加的修改方案。

原代码

import random
roll_list = []  #empty list for appending rolls
num_rolls = 100 #number of times the program will run

def init_list(): #defines initial list for possible outcomes
    for x in range(0,13):
      roll_list.append(0)

def roll_dice(): #rolls the dice and sums the outcomes
    dice1 = random.randint(1,6)#random operator to make all rolls random 1-6
    dice2 = random.randint(1,6)
    roll = dice1 + dice2 #sum of each roll 
    return roll  #keeps the program in this loop

def update_list(roll): #defines updated list of possible outcomes
    previousvalue = roll_list.pop(roll)
    roll_list.insert(roll,previousvalue + 1)


def print_histogram(): #defines the for loop below, printing the desired outcome
  for numbers in range(2, 13):
    print((numbers), 's', ':', '*' * roll_list[numbers])

# main program
init_list() #executeds first def, list of values 2-12
for y in range(0,num_rolls): #excecutes second def, roll dice, 100 times
  update_list(roll_dice())#executes third def, updated list 100 values long

print_histogram() #excecutes fourth def, printing desired outcome

当前输出

2 s : ****
3 s : ***
4 s : ************
5 s : ***********
6 s : ******************
7 s : ************
8 s : ************
9 s : **********
10 s : **********
11 s : ****
12 s : ****

期望输出

2s: *****
3s: *********
4s: *******
5s: ****
6s: ************
7s: *****
8s: **********
9s: **
10s: ********
11s: ****
12s: *************

修改方案

问题出在print_histogram函数里的print语句——用逗号分隔多个参数时,Python会自动在参数之间添加空格。只需要把输出内容拼接成一个字符串即可,最简单的方式是使用f-string:

将原函数中的这一行:

print((numbers), 's', ':', '*' * roll_list[numbers])

替换为:

print(f"{numbers}s: {'*' * roll_list[numbers]}")

或者使用字符串拼接的方式:

print(str(numbers) + 's:' + '*' * roll_list[numbers])

这样就能让数字、's'和':'紧密连接,不再出现多余空格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 00:55:14