在python中遇到TypeError: can only concatenate str (not “int“) to str的解决方法

2022/2/14 9:11:41

本文主要是介绍在python中遇到TypeError: can only concatenate str (not “int“) to str的解决方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

错误描述TypeError: can only concatenate str (not "int") to str
原因:在python中拼接字符串较为特殊,整型变量与字符串不能直接拼接,需要采用通过(%)操作符拼接
解决办法

  1. 通过str.format()方法拼接
  2. 通过(%)操作符拼接(此种方法较为常用)

例如:

错误的:

alarm_content += host_ip + "的cpu " + cpu_info + "超过了阈值" + threshold_cpu

修改为:

alarm_content += "%s" % host_ip + "的cpu " + "%d" % cpu_info + "超过了阈值" + "%d" % threshold_cpu

(注:第32次发文,如有错误和疑问,欢迎在评论区指出!)
——2022.2.14



这篇关于在python中遇到TypeError: can only concatenate str (not “int“) to str的解决方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程