首页 > 解决方案 > 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 的类型,但仍然有错误

标签: python-3.x

解决方案


这里的问题是,nint您尝试将其与'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)


推荐阅读