如何删除python中的额外空间?

问题描述:

这是我的一些Python代码:如何删除python中的额外空间?

my_fancy_variable = input('Choose a color to paint the wall:\n') 

if my_fancy_variable == 'red': 
    print(('Cost of purchasing red paint:\n$'),math.ceil(paint_needed) * 35) 
elif my_fancy_variable == 'blue': 
    print(('Cost of purchasing blue paint:\n$'),math.ceil(paint_needed) * 25) 
elif my_fancy_variable == 'green': 
    print(('Cost of purchasing green paint:\n$'),math.ceil(paint_needed) * 23) 

我只是想摆脱“$”之间的空间和“105

有更多的代码,但基本上我会得到一个结果: Cost of purchasing red paint: $ 105

感谢

+0

@CaptainTrunky这个问题涉及到Python 2 –

打印功能有一个默认的说法,sep,这是考虑到打印本功能每个参数之间的分隔符离子。

默认情况下,它被设置为一个空格。您可以轻松地这样修改它,(在你的情况没有什么):

print('Cost of paint: $', math.ceil(paint_needed), sep='') 
# Cost of paint: $150 

如果你想每个参数以换行符分开,你可以这样做:

print('Cost of paint: $', math.ceil(paint_needed), sep='\n') 
# Cost of paint: $ 
# 150 

sep可您需要(或想要)的任何字符串值。

+0

我相信这个问题想与 –

+0

我回答第二个例子中,整条生产线后的金额和换行的美元符号 –

我会用格式化字符串的可读性:

f"Cost of purchasing blue paint: ${math.ceil(paint_needed) * 25}" 

另一个这里关键是你有多少IFS要补充的吗?靛蓝/橙色等

colours = { 
    'red': "$35", 
    'blue': "$25", 
    'green': "$23" 
} 

cost = colours.get(my_fancy_variable, "Unknown cost") 

print(f"Cost of purchasing {my_fancy_variable} is {cost}")