不确定如何从字符串中删除空格

问题描述

current_price = int(input())
last_months_price = int(input())


print("This house is $" + str(current_price),'.',"The change is $" +
      str(current_price - last_months_price) + " since last month.")
print("The estimated monthly mortgage is ${:.2f}".format((current_price * 0.051) / 12),'.')

这将产生:

This house is $200000 . The change is $-10000 since last month.
The estimated monthly mortgage is $850.00 .

我不确定如何删除"$200000""$850.00"之后的空白。我不完全了解strip()命令,但是从我的阅读中,它对于解决此问题没有帮助。

解决方法

您可以给print一个附加参数:sep,如下所示:

print("This house is $" + str(current_price),'.',"The change is $" +
      str(current_price - last_months_price) + " since last month.",sep='')

因为默认值是逗号后的空白。

,

也许尝试f弦注射

print(f"This house is ${current_price}. The change is ${current_price - last_months_price} since last month.")

f-string(带格式的字符串)提供了一种使用最小语法在字符串文字中嵌入表达式的方法。这是连接字符串的一种简化方法,而不必显式调用str来格式化字符串以外的数据类型。

如下面的@Andreas所述,您也可以将sep=''传递给print,但这需要您将其他字符串与正确格式化的空格连接起来。