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.
[toc]
How to concatenate string and int in Python
Let’s first try to use + operator to concatenate string and int.
strOne = "one" intOne = 1 strInt = strOne + intOne print(strInt)
Output:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last)in 1 strOne = "one" 2 intOne = 1 ----> 3 strInt = strOne + intOne 4 print(strInt) TypeError: can only concatenate str (not "int") to str
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.
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.
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.
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.
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.
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.
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.
list1 =[1,2,3] + {5,6,7}
Output:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last)in ----> 1 list1 =[1,2,3] + {5,6,7} TypeError: can only concatenate list (not "set") to list
As you can see, you can not concatenate list and set using + opertor.