Concatenate String and Int in Python

We consider this article to be an extension to the article – Concatenate Strings in Python. In that article, we discussed how to concatenate two strings using the operator +. Here, we would discuss how to Concatenate String and Int in Python.

First, we would show what issue we would receive if we use + operator while concatenating a string and int.

So, let’s say we have a string variable s1 = “Hello”

and, int variable s2 = 2022

Now, if try to concatenate these two using + operator –

>>> s1 = "Hello "
>>> s2 = 2022
>>> x=s1+s2

It would throw an error at this stage –

TypeError: can only concatenate str (not "int") to str

But, there are few workarounds. We will discuss str() function here. The str() function mainly helps convert the integer value to string. In addition to, the compiler also interprets it as a string value.

Repeating the above example with some modifications –

>>> s1 = "Hello "
>>> s2 = str(2022)
>>> x=s1+s2
>>> print(x)

The output of the above code would be –

Hello 2022

In conclusion, we have discussed how to Concatenate string and int in Python.

Additional Info –

Let’s see what happens if we add two integer values with str() function. We would again use the above example with some modifications –

>>> s1 = str(2021)
>>> s2 = str(2022)
>>> x=s1+s2
>>> print(x)

Ideally, if we don’t use the str() function – it would return with the addition of these two numbers. But, with str() function it would treat the above two values as strings. And, return with the following output –

20212022