Python字符串与数字拼接

Python不像JS或者PHP这种弱类型语言里在字符串连接时会自动转换类型,而是直接报错。要解决这个方法只有提前把int转成string,然后再拼接字符串即可。

如代码:

1
2
3
4
5
# coding=utf8
str = '你的分数是:'
num = 82
text = str+num+'分 | 琼台博客'
print text

执行结果

python数字与字符串拼接

直接报错:TypeError: cannot concatenate 'str' and 'int' objects

解决这个方法只有提前把num转换为字符串类型,可以使用bytes函数把int型转换为string型。

代码:

1
2
3
4
5
6
# coding=utf8
str = '你的分数是:'
num = 82
num = bytes(num)
text = str+num+'分 | 琼台博客'
print text

结果搞定:

python字符串与数字拼接报错解决

原文地址:https://www.cnblogs.com/tina-smile/p/3616656.html