首页 > 解决方案 > 格式化字符串输出以避免空格

问题描述

我需要修改这段代码以消除它$和它后面的数量之间的空间。这是当前的输出:

Choose a color to paint the wall:
Cost of purchasing red paint: $ 35

Choose a color to paint the wall:
Cost of purchasing blue paint: $ 75

这就是我想要的样子:

Choose a color to paint the wall:
Cost of purchasing red paint: $35  

Choose a color to paint the wall:
Cost of purchasing blue paint: $75

我的代码如下:

import math

# Dictionary of paint colors and cost per gallon
paintColors = {
   'red': 35,
   'blue': 25,
   'green': 23
}

wallHeight = float(input('Enter wall height (feet):\n'))
wallwidth = float(input('Enter wall width (feet):\n'))
wallArea = float(wallHeight * wallwidth)
print('Wall area:', int(wallArea), 'square feet')

paintNeeded = wallArea / 400
print('Paint needed: %f' % paintNeeded, 'gallons')
cansNeeded = math.ceil(paintNeeded)
print('Cans needed:', cansNeeded,'can(s)\n')

print('Choose a color to paint the wall:')
paintColor = input()

paintcost = {'red':35,'blue':75}
print('Cost of purchasing', paintColor, 'paint: $',  paintcost[paintColor])

标签: pythonpython-3.x

解决方案


将最后一行替换为

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

推荐阅读