TypeError: __str__ returned non-string (type int) in Python

avatar

Borislav Hadzhiev

Wed Apr 20 20221 min read

banner

Photo by Jackson David

TypeError: __str__ returned non-string (type int) in Python #

The Python "TypeError: __str__ returned non-string (type int)" occurs when we return an integer value from the __str__() method. To solve the error, use the str() class to convert the integer to a string before returning it.

typeerror str returned non string type int

Here is an example of how the error occurs.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __str__(self): return self.salary # 👈️ this is an integer emp = Employee('Bob', 75) # ⛔️ TypeError: __str__ returned non-string (type int) print(emp)

We returned an integer from the __str__() method, but the method must return a string.

Use the str() class to convert the integer to a string before returning it.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __str__(self): return str(self.salary) # 👈️ convert to str emp = Employee('Bob', 75) print(emp) # 👉️ 75

The return value of the __str__() method must be a string object.

You can use a formatted string literal if you need to include expressions in a string.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __str__(self): return f'Employee salary: {self.salary}' emp = Employee('Bob', 75) print(emp) # 👉️ Employee salary: 75
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

Make sure to wrap expressions in curly braces - {expression}.

The __str__() method is called by str(object) and the built-in functions format() and print() and returns the informal string representation of the object.

Use the search field on my Home Page to filter through my more than 1,000 articles.