Home > Article > Backend Development > How to solve the error when concatenating strings and numbers in Python
Foreword
As we all know, Python is not like JS or PHP, which is a weakly typed language that automatically converts types when strings are connected. If you directly concatenate strings and numbers, an error will be reported directly.
Such as the following code:
# coding=utf8 str = '你的分数是:' num = 82 text = str+num+'分 | 琼台博客' print text
Execution results
Report an error directly: TypeError: cannot concatenate 'str' and 'int' objects
The only way to solve this problem is to convert num to string type in advance. You can use the bytes function to convert int type to string type.
Code:
# coding=utf8 str = '你的分数是:' num = 82 num = bytes(num) text = str+num+'分 | 琼台博客' print text
The result is done:
Summary
The above is all about solving string and number splicing errors in Python. I hope the content of this article can be helpful to everyone in learning or using python. If you have any questions, you can leave a message to communicate.