在试图删除打印中某个内容之间的空格时卡住了()

  • 本文关键字:空格 之间 删除 打印 python
  • 更新时间 :
  • 英文 :


很抱歉提前回答一个非常简单的问题,我是python的新手。

我有一个项目正在进行中,该项目接受了关于房间大小、材料/安装成本的投入,并输出了所需材料的成本和数量。

我已经做好了所有的工作,但我不能让我的输出中的美元符号出现在输出旁边,它们总是出现在一个空格之外。(400.00美元(。我知道我可以在某个地方加一个加号来把两者结合在一起,但我尝试的时候总是出错。我不太确定我做错了什么,但如果有任何意见,我将不胜感激。我将在下面粘贴工作正常且没有错误的代码。我在线条之间加了空格,这样可以看得更清楚。

wth_room = (int(input('Enter the width of room in feet:')))
lth_room = (int(input('Enter the length of room in feet:')))
mat_cost = (float(input('Enter material cost of tile per square foot:')))
labor = (float(input('Enter labor installation cost of tile per square foot:')))
tot_tile = (float(wth_room * lth_room))
tot_mat = (float(tot_tile * mat_cost))
tot_lab = (float(labor * tot_tile))
project = (float(mat_cost + labor) * tot_tile)
print('Square feet of tile needed:', tot_tile, 'sqaure feet')
print('Material cost of the project: $', tot_mat)
print('Labor cost of the project: $', tot_lab)
print('Total cost of the project: $', project)

您可以将分隔符更改为空字符串(默认为空格(。

print('Material cost of the project: $', tot_mat, sep='')
print('Labor cost of the project: $', tot_lab, sep='')
print('Total cost of the project: $', project, sep='')

使用以下内容:

print('Total cost of the project: $'+str(project))

注意:我已经用str函数将项目转换为字符串,因为它是float。你们可以对所有人使用相同的。

您也可以尝试使用fstring语法(假设您使用的是Python 3(

print(f'Material cost of the project: ${tot_mat}')

,替换为+,因为默认情况下,会留下一个空格,例如:

print('Material cost of the project: $' + tot_mat)
print('Labor cost of the project: $' + tot_lab)
print('Total cost of the project: $' + project)

您也可以按如下方式使用f-strings

print(f'Material cost of the project: ${tot_mat}')
print(f'Labor cost of the project: ${tot_lab}')
print(f'Total cost of the project: ${project}')

除了其他答案外,还要注意,如果有人输入了任何不正确的内容,您的代码都会崩溃(例如,如果您试图将其解析为浮点值,"3,9"将抛出错误(。考虑阅读try/except,在input()函数的上下文中捕获和处理错误。

最新更新