python - 我收到一条我不太明白的错误消息
问题描述
我正在开发一个程序,我收到一条错误消息,上面写着:
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")
对奇怪的变量名感到抱歉
解决方案
该错误表示+
不允许将字符串(与)连接到整数。其他语言(想到 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))
这是等效的,只是更长一点并且不那么清楚。
推荐阅读
- django - 如何在消费者、django 通道 2 中创建连续发送数据并安全断开连接的任务?
- node.js - 错误:在将标头发送到客户端后无法设置标头
- javascript - 为什么 Android Chrome 上的 createImageBitmap 会缩小我的图像?
- java - 键盘中断布局和行为
- sql-server - 通过 Where in 获取每个 Id 的前 1 行
- shell - 如何让 Terraform 执行包含 sed 命令的 virtual_machine_extension?
- java - 如何根据表中同一行的其他元素的文本值获取元素的文本?
- internet-explorer-11 - 为什么在尝试生成 GOJS 图时在 IE11 中出现语法错误
- python - 如果列中的总和等于 n,则将 n 行作为输入并返回列名的函数
- python-3.x - 在 azure databricks 中使用 validate_email 包验证电子邮件以获取 300k 条记录导致超时错误