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

如何修改Python代码消除打印输出中$符号与金额之间的多余空格

消除Python打印输出中$符号与金额间多余空格的解决方案

问题原因

你当前代码最后一行的print函数用逗号分隔多个输出参数,Python的print函数默认会在逗号分隔的不同参数之间自动添加空格,因此$和后面的金额数值之间就出现了多余空格。

修复方法

推荐直接使用字符串格式化来拼接输出内容,避免默认空格的问题,常用方案如下:

方案1:使用f-string(Python3.6+支持,写法最简洁)

将最后一行打印代码替换为:

print(f'Cost of purchasing {paintColor} paint: ${paintcost[paintColor]}')

方案2:使用%格式化

print('Cost of purchasing %s paint: $%d' % (paintColor, paintcost[paintColor]))

方案3:使用str.format()方法

print('Cost of purchasing {} paint: ${}'.format(paintColor, paintcost[paintColor]))

修改后的完整代码

import math

# 油漆颜色和每加仑成本的对应字典
paintColors = {
   'red': 35,
    'blue': 25,
    'green': 23
}

wallHeight = float(input('输入墙面高度(英尺):\n'))
wallwidth = float(input('输入墙面宽度(英尺):\n'))
wallArea = float(wallHeight * wallwidth)
print('墙面面积:', int(wallArea), '平方英尺')

paintNeeded = wallArea / 400
print('需要油漆量:%f' % paintNeeded, '加仑')
cansNeeded = math.ceil(paintNeeded)
print('需要桶数:', cansNeeded,'桶\n')

print('选择墙面刷漆的颜色:')
paintColor = input()

paintcost = {'red':35,'blue':75}
# 已修改打印逻辑,消除$和金额间的空格
print(f'购买{paintColor}油漆的成本:${paintcost[paintColor]}')

修改后运行代码即可得到你期望的输出效果,$符号与金额数值之间不会再出现多余空格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 01:00:02