Fix: TypeError: can only concatenate str (not int) to str in Python


Python TypeError - can only concatenate str (not int) to str

TypeError error will occur when you try to concatenate a string and an integer in your Python.

This is because when you have a string and an int value (even when you are doing it in a print() function) Python will consider it as an addition and thus will not allow adding a string to an integer as they are two different data types.

Error Code Example:
name = "Sam"
age = 23

print("Hello " + name + " you are " + age + " years old!")

Error:
Traceback (most recent call last):
  File "/Users/code2care/PycharmProjects/python-learnings/venv/0-test.py", line 4, in <module>
    print("Hello "+ name + "you are " + age + "year old!")
TypeError: can only concatenate str (not "int") to str

Fix:

All you need to do is wrap your numerical int value with a str() to convert it into a string first so that it is considered as a "string concatenation" and not ints

Example: Code fix
name = "Sam"
age = 23

print("Hello "+ name + " you are " + str(age) + " years old!")
Output:

Hello Sam you are 23 years old!

Fix - Python TypeError - can only concatenate str (not int) to str

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap