Python 中 "TypeError: can only concatenate str (not 'int') to str" 错误解决

在 Python 代码中,当你尝试使用 print() 函数拼接字符串时,如果其中包含整数,可能会遇到 TypeError: can only concatenate str (not 'int') to str 错误。

错误原因:

这个错误通常发生在将字符串与非字符串类型(例如整数)进行拼接时。Python 中的字符串拼接操作只能在两个字符串之间进行,而 len(li_list) 函数返回的是一个整数,而不是字符串。

解决方案:

为了解决这个问题,你需要将整数转换为字符串。可以使用 str() 函数将整数转换为字符串,然后再进行拼接。

修改代码:

print('一级' + str(len(li_list)) + target)

示例:

li_list = [1, 2, 3]
target = '目标'

# 错误代码
# print('一级' + len(li_list) + target)

# 正确代码
print('一级' + str(len(li_list)) + target)

输出:

一级3目标

通过使用 str() 函数将 len(li_list) 转换为字符串,你就可以成功地将字符串、整数和变量拼接起来。


原文地址: https://www.cveoy.top/t/topic/pR7W 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录