Python 3 类(class),在打印语句末尾的句点之前有额外空间问题

标签 python python-3.x

我正在学习 python 入门类(class),所以这些东西仍然是相当基础的,但我们将不胜感激任何帮助。

我试过很多东西,我知道打印语句中的逗号会自动添加一个空格,但我无法添加加号和句点而不会出错

这是我的代码:

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 退出

最佳答案

使用 f-strings :

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)

关于Python 3 类(class),在打印语句末尾的句点之前有额外空间问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66322684/

相关文章:

python - Groupby - 如何将逻辑检查结果应用于所有行

python - 如何使用装饰器将函数绑定(bind)到对象实例?

Python 相当于 PHP 的空合并运算符和速记三元运算符?

python - 如何按字母顺序组织以特定字母开头的字符串列表?

python - 如何在websocket python中发送 'Headers'

python - 来自 Dataframe 的条形图

python - 如何找到坐标所在道路网的链接? ( map 匹配)

python - 如何将包含跨越多列的单元格的 html 表格转换为 Python 3 中的列表列表?

python - 如何从 len()、str.format() 和零宽度空间获得合理的结果?

python - 如何在 python 中使用 pip