首页 > 解决方案 > Python 3课程,在打印语句末尾的句点之前有额外的空间问题

问题描述

我正在学习 python 介绍课程,所以这些东西仍然相当基础,但任何帮助将不胜感激。

我尝试了多种方法,我知道打印语句中的逗号会自动添加一个空格,但是我无法添加加号和句点而不会出错

这是我的代码:

bonus = survey_completers / class_size

avg = my_current_average + bonus

rounded_bonus = round(bonus, 1)

rounded_avg = round(avg, 1)

textOne = str("After the")

textTwo = str("point bonus, my average is")

textThree = str(".")

print(textOne, rounded_bonus, textTwo, rounded_avg, textThree)

给出输出:

After the 0.5 point bonus, my average is 87.6 .

当预期输出是句号正好在 87.6 后面的那句话时


我已经尝试过诸如:

bonus = survey_completers / class_size

avg = my_current_average + bonus

rounded_bonus = round(bonus, 1)

rounded_avg = round(avg, 1)

textOne = str("After the")

textTwo = str("point bonus, my average is")

print(textOne, rounded_bonus, textTwo, rounded_avg + ".")

这给了我这个错误:

Traceback (most recent call last):
File "CIOSBonus.py", line 40, in <module>
print(textOne, rounded_bonus, textTwo, rounded_avg + ".")
TypeError: unsupported operand type(s) for +: 'float' and 'str'

命令以非零状态退出 1

标签: pythonpython-3.x

解决方案


使用f 字符串

bonus = survey_completers / class_size

avg = my_current_average + bonus

rounded_bonus = round(bonus, 1)

rounded_avg = round(avg, 1)

result = f"After the {rounded_bonus} point bonus, my average is {rounded_avg}."

print(result)

推荐阅读