如何消除Python print语句中的多余空白?
解决Python print输出多余空白的问题
问题原因
你当前的代码多次调用print,并且在print中用逗号分隔多个输出元素——Python的print函数默认会在逗号分隔的元素之间自动添加空格,再加上你设置了end=' '手动添加空格,两种空格叠加就导致了大量多余空白。
修复方案
用**f-string(格式化字符串)**把需要输出的内容整合成一个字符串,一次性输出,这样能完全控制文本格式,避免自动添加的空格。修改后的代码如下:
current_price = int(input()) last_months_price = int(input()) change = current_price - last_months_price mortgage = (current_price * 0.051) / 12 print(f'This house is ${current_price}. The change is ${change} since last month.') print(f'The estimated monthly mortgage is ${mortgage:.2f}.')
修复后输出示例
假设输入为200000和210000,输出会变成:
This house is $200000. The change is $-10000 since last month. The estimated monthly mortgage is $850.00.
其他可选方案
如果你不想合并成一个print语句,也可以去掉print中的逗号,直接用字符串拼接(但f-string更简洁易读):
print('This house is $' + str(current_price) + '. ' + 'The change is $' + str(change) + ' since last month.') print('The estimated monthly mortgage is $' + f'{mortgage:.2f}' + '.')
内容的提问来源于stack exchange,提问作者maddy
相关产品推荐
相关产品推荐

