TypeError: Can't convert 'int' object to str implicitly

A TypeError can occur if the type of an object is not what the Python interpreter expected to see. This error is a common mistake made by beginning developers is to use the '+' operator between values of incompatible types. This error message Can't convert 'int' object to str implicitly is clear, when concatenating strings with integers - you can't directly stick together a string and an integer. So, in order to resolve this problem, you have to explicitly parse the integer to a string by the str() built-in function .

what is Can't convert 'int' object to str implicitly


days=10 print("Total number of days: " + days)


Traceback (most recent call last): File "sample.py", line 2, in <module> print("Total number of days: " + days) TypeError: Can't convert 'int' object to str implicitly

The TypeError is generated because '+' (addition) does not work between an integer and a string. Unlike many other programming languages out there, Python does not implicitly typecast integers (or floats) to strings when concatenating with strings. Fortunately, Python has a built-in function str() which will convert the parameter passed in to a string format.

There are 3 ways to resolve this problem:

  1. print ("Total number of days: " + str(days))
  2. print ("Total number of days: ", days)
  3. print ("Total number of days: {}".format(days))

print("Total number of days: " + days)

Python interpreter reads through the entire line and notices a use of '+'. Python consider the type of the left operand , "Total number of days: " and conclude that it is a 'string'. Then it considers the type of the right operand (days), which is an integer. Python then produces an error, because it does not know how to add string and integer. Because of this, you can explicitly convert the integers to strings by the str() function . Conversion to a string is done with the builtin str() function, which basically calls the __str__() method of its parameter.

TypeError: Can't convert 'int' object to str implicitly

Note that when something goes wrong while the Python interpreter runs your script, the interpreter will stop and will generate a traceback (or stack trace) that displays all functions that were running when the error occurred. This error Can't convert 'int' object to str implicitly occurs when a function or operator cannot be applied to the given values, due to the fact that the value's type is inappropriate. This can happen when two incompatible types are used together.

Python Type Conversion

how to Python Type Conversion

The process of converting the value of one data type (integer, string etc.) to another data type is called type conversion. More on... Python Type Conversion .