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
How to concatenate string and int in Python
Let’s first try to use +
operator to concatenate string and int.
1 2 3 4 5 6 |
strOne = "one" intOne = 1 strInt = strOne + intOne print(strInt) |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 |
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-5-7b8584e65471> in <module> 1 strOne = "one" 2 intOne = 1 ----> 3 strInt = strOne + intOne 4 print(strInt) TypeError: can only concatenate str (not "int") to str </module></ipython-input-5-7b8584e65471> |
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.
1 2 3 4 5 6 |
strOne = "one" intOne = 1 strInt = strOne + str(intOne) print(strInt) |
Output:
Using format()
You can also use format()
function to concatenate string and int.
Here is an example.
1 2 3 4 5 6 |
strTwo = "two" intTwo = 2 strInt = "{}{}".format(strTwo,intTwo) print(strInt) |
Output:
Using % operator
You can also use %
operator to concatenate string and int.
Here is an example.
1 2 3 4 5 6 |
strThree = "three" intThree = 3 strInt = "%s%s"%(strThree,intThree) print(strInt) |
Output:
Using repr() operator
repr()
provides printable representation of the object.
Here is an example.
1 2 3 4 5 6 |
strSix = "Six" intSix = 6 strInt = strSix + repr(intSix) print(strInt) |
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.
1 2 3 4 5 6 |
strFour = "four" intFour = 4 strInt = f'{strFour}{intFour}' print(strInt) |
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.
1 2 3 4 5 |
strFive = "Five" intFive = 5 print(strFive,intFive, sep="") |
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.
1 2 3 |
list1 =[1,2,3] + {5,6,7} |
Output:
1 2 3 4 5 6 7 8 9 |
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-17-ff3ed0939f93> in <module> ----> 1 list1 =[1,2,3] + {5,6,7} TypeError: can only concatenate list (not "set") to list </module></ipython-input-17-ff3ed0939f93> |
As you can see, you can not concatenate list and set using +
opertor.