This tutorial teaches how to concatenate string and int in Python
In other languages such as Java, C++, etc, you can concatenate string and int using + operator, but you can not do the same in python.
Table of Contents [hide]
How to concatenate string and int in Python
Let’s first try to use +
operator to concatenate string and int.
Output:
There are multiple ways to concatenate string and int in Python.
Using str()
Best way to convert intOne to str using str() function.
Here is an example.
Output:
Using format()
You can also use format()
function to concatenate string and int.
Here is an example.
Output:
Using % operator
You can also use %
operator to concatenate string and int.
Here is an example.
Output:
Using repr() operator
repr()
provides printable representation of the object.
Here is an example.
Output:
Using f-strings
You can also use f-strings operator to concatenate string and int from python 3.6 onwards.
Here is an example.
Output:
Print String and int together
If you just wanted to print String and int together, you can use print()
with sep=""
.
Here is an example.
Output:
Why can’t we use + operator to concatenate string and int
In python, +
can be used for adding two numbers or concatenate the sequences.
As a rule, python does not convert objects implicitly from one to another while using the operator, so it may be confusing what exactly you want to do with +
operator.
2 + ‘3’ can be either ’23’ or 5, so python does not support + operator to concatenate string and int.
You can not concatenate sequences of different types using + operator in Python.
Output:
As you can see, you can not concatenate list and set using +
opertor.