我收到了一条我不太明白的错误信息

2024-06-08 22:43:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个程序,收到一条错误消息,上面说:

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

我认为这意味着我必须将变量从int改为string,但当我尝试时,它不起作用。后来我想可能是我没有正确理解错误信息。你知道吗

以下是一些上下文代码:

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")

抱歉,变量名太奇怪了


Tags: thetoforindexminwillintprint
3条回答

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

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

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

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

这是相当的,只是有点长,不太清楚。你知道吗

正如前面提到的@ferdbugs,您可以将任何值强制转换为string类型。
您的代码应该看起来像这样

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 " + str(shortesttime) + "minutes")

希望这有帮助!一定要让我知道在评论中,如果你仍然得到相同的错误或不同的错误。你知道吗

请记住:要连接多个字符串,您可能只需要连接多个字符串。例如,不能将intstr连接起来。你知道吗

所以要打印它,必须将它转换成string,在python世界中称为str。你知道吗

在第四行,将其改为:print("I will set a timer for " + str(shortesttime) + "minutes")

另一种方式是格式化字符串:

就像这样,print(f"I will set a timer for {shortesttime} minutes")。格式化字符串会自动将任何数据类型转换为字符串。你知道吗

相关问题 更多 >