How to Solve TypeError: must be str, not int in Python

To solve TypeError: must be str, not int in Python, use the str() function. The str() is a built-in Python function that converts the specified value into a string. This TypeError is a standard error raised when an int number is concatenated with a string. The TypeError occurs in the print() function’s output most of the time.

We print a description and then print the number. For example, we will print like “the sum of two numbers is ” + a+b. This can be easily solved by converting the number into a string. This is not a critical error. This is just an indication that the user has printed the number and the string.

To concatenate strings in Python, use the “+” operator.

a = "Hello "
b = "World"
c = a+b
print(c)

Output

Hello World

If you use the + operator among numbers, it will add the numbers.

a = 5
b = 6
c = a+b
print(c)

Output

11

The above code will generate an output of 11. This is just a simple addition operation. Now let us consider a situation where we concatenate two numbers.

a = "5"
b = "6"
c = a+b
print(c)

Output

56

The output is 56. Hence in this example, we can see that the two numbers are concatenated into a single string. When two numbers are given in the string format, they are concatenated using the + symbol.

Let’s write a code where we get TypeError: must be str, not int.

a = "5"
b = 10
c = a + b
print(c)

Output

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

When we execute this program, it raises an error called the TypeError: must be str, not int. This error is thrown when we concatenate the string with an integer number. To solve this TypeError, convert an integer to a string using the str() function.

a = "5"
b = 10
c = a + str(b)
print(c)

Output

510

This code outputs 510. We have converted a variable b as a string and then perform the concatenation operation.

Conclusion

The TypeError: must be str, not int occurs only when we concatenate int with string. To solve this error, use the convert the int number into a string and then perform the concatenation operation.

That’s it for this tutorial.

See also

TypeError: ‘float’ object is not iterable

TypeError: list indices must be integers or slices, not str

TypeError: Only size-1 arrays can be converted to Python scalars

Leave a Comment