by Sai gowtham

Python - Can only concatenate str (not int) to str

In this tutorial, we are going to learn about how to solve the TypeError: can only concatenate str (not “int”) to str in Python

When we try to concatenate a string and integer, we will get the TypeError: can only concatenate str (not “int”) to str, because in python we only concatenate if both values belong to the same data type.

Here is an example of how the error occurs:

name = 'John' # string
id = 11    # integer

result = name + id
print (result)

Output:

Traceback (most recent call last):
  File "main.py", line 15, in <module>
    print (name + id)
TypeError: can only concatenate str (not "int") to str

In the example above, we are concatenating the string and integer using + plus operator but both are different data types.So it throws the error in terminal.

To solve the error, convert the integer value to a string using str() function then concatenate it using + operator.

The str() function takes the integer value as a argument and converts it to the string.

Here is an example:

name = 'John' # string
id = 11    # integer

result = name + str(id)
print (result)

Output:

'John11'

Conclusion

The “can only concatenate str (not int) to str” error occurs, when we try to concatenate the string and integer. To solve the error, convert the integer to a string using the str() function then add it to the string.

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2022 (Beginner + Advanced)
JavaScript - The Complete Guide 2022 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY