DEV Community

Monika Pareek
Monika Pareek

Posted on

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

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

Ever encountered this Python error?

age = 25
print("My age is " + age)
Enter fullscreen mode Exit fullscreen mode

You run the code and suddenly get:

TypeError: can only concatenate str (not "int") to str
Enter fullscreen mode Exit fullscreen mode

Don't worry! This is one of the most common mistakes Python beginners encounter.

Let's understand why it happens and how to fix it.

Why Does This Error Happen?

In Python, strings and integers are different data types.

  • "Hello" is a string.
  • 25 is an integer.

Python does not allow you to directly concatenate a string and an integer using the + operator.

That's why this code fails:

print("My age is " + 25)
Enter fullscreen mode Exit fullscreen mode

3 Ways to Fix This Error

1. Convert the Integer to a String

Use str() to convert the integer into a string.

age = 25
print("My age is " + str(age))
Enter fullscreen mode Exit fullscreen mode

Output:

My age is 25
Enter fullscreen mode Exit fullscreen mode

2. Use an f-string (Recommended)

Python f-strings provide a cleaner way to combine text and variables.

age = 25
print(f"My age is {age}")
Enter fullscreen mode Exit fullscreen mode

Output:

My age is 25
Enter fullscreen mode Exit fullscreen mode

3. Use String Formatting

You can also use the format() method.

age = 25
print("My age is {}".format(age))
Enter fullscreen mode Exit fullscreen mode

Output:

My age is 25
Enter fullscreen mode Exit fullscreen mode

How to Avoid This Error in the Future

Here are a few useful tips:

  • Understand the difference between strings and integers.
  • Use str() when converting numbers into text.
  • Prefer f-strings for readable Python code.
  • Check variable types using type() when debugging.

Example:

age = 25
print(type(age))
Enter fullscreen mode Exit fullscreen mode

Bonus: Fix Python Errors with AI

Sometimes Python errors are more complicated than a simple type mismatch.

Instead of spending hours searching for solutions, you can try an AI-powered debugging tool.

I built XoneAI Python Error Fixer to help developers understand and fix Python errors.

Just paste your Python traceback and try it.

Try it free: https://www.xoneai.in/tools/python-error-fixer

  • No signup required
  • No login required
  • Free to try

Disclosure: I'm the developer behind XoneAI. I built this tool to make everyday debugging easier for developers and students.

Final Thoughts

Python errors are part of learning to code. The important thing is understanding why they happen rather than simply copying a solution.

Have you encountered this TypeError before? What's your favourite way to handle it?

Share your experience in the comments!

Top comments (0)