python-3.x - python TypeError:只能将str(不是“int”)连接到str
问题描述
import time
for i in range(2,6):
start = time.time()
n=i
end = time.time()
print(n)
time_cost=end-start
print(type(time_cost))
print('totally cost for '+n+'*'+n,str(time_cost))
我使用 str 更改 time_cost 的类型,但仍然有错误
解决方案
这里的问题是,n
当int
您尝试将其与'totally cost for '
您必须将最后一个打印语句替换为:
print('totally cost for '+str(n)+'*'+str(n), str(time_cost))
如果您不调用也可以str()
,time_cost
因为它是一个不同的参数,因此print()
会自动转换它。n
未转换,因为使用+
运算符显式连接。
所以最终的打印可以是:
print('totally cost for '+str(n)+'*'+str(n), time_cost)
推荐阅读
- javascript - ajax,当它具有不同的值时,我得到相同的值
- javascript - 使用 angular '[attr.aria-hidden]' 隐藏的标签仍然可以使用 tab 访问和点击并输入
- excel - 如果另一个范围包含特定文本,如何对来自两个范围的数据求和
- wordpress - Wordpress 的新 Gutenberg 中的自定义模板页面
- javascript - 电报机器人(telegraf.js 库)将消息从一个通道方法转发到另一个通道方法?
- c# - 什么Android是蓝屏?
- reactjs - React Hooks 如何使用Callback“冻结”闭包?
- apache-spark - Spark Streaming、Structured Streaming 和 Kafka Streaming 是一回事吗?
- bash - 我可以使用 cut 来设置变量吗?
- google-cloud-platform - 为什么在列出 BQ 作业时使用 VM 实例中的服务帐户