首页 > 解决方案 > 我收到一条我不太明白的错误消息

问题描述

我正在开发一个程序,我收到一条错误消息,上面写着:

print("I will set a timer for " + shortesttime + "minutes")
TypeError: can only concatenate str (not "int") to str

我认为这意味着我必须将变量从 int 更改为字符串,但是当我尝试它时它不起作用。后来我只是想也许我没有正确理解错误信息。

这是上下文的一些代码:

shortesttime = hwt.index(min(hwt))
smallesthwitem = (uhw[hwt.index(min(hwt))]) #it's finding the position of the smallest item in homeworktime and then, for example if the place of that was 2 it would find what's at the second place in uhw
print("So let's start with something easy. First you're going to do " + smallesthwitem)
print("I will set a timer for " + shortesttime + "minutes")

对奇怪的变量名感到抱歉

标签: python

解决方案


该错误表示+不允许将字符串(与)连接到整数。其他语言(想到 BASIC)可以让你做到这一点。最好的办法是使用格式化程序。如果你想要一个简单的格式,那么你只需要:

print(f"I will set a timer for {shortesttime} minutes")

格式化程序中有选项可以为数千和其他内容添加逗号,但这比使用类型转换更容易。这种格式是在 python 3.6 中引入的(称为 f-strings)。如果您介于 3.0 和 3.5 之间,请使用

print("I will set a timer for {} minutes".format(shortesttime))

这是等效的,只是更长一点并且不那么清楚。


推荐阅读