Convert an object to string in Python

If you create a variable, you can easily convert it to a string using the print function.

The variable is an integer, that is converted to string with the print function. Therefore you don’t have to convert it to a string before printing.

If you join variable with text, then you have to convert this variable to string before printing.

Otherwise, the interpreter will return the following error:

The correct code:

Run this code. The interpreter will return the following string:

Inside the print function, there is another function, called str. It tries to convert everything to string. Now, there is no problem in merging this variable with other strings inside the print function.

Convert a class object to a string

Converting simple objects, like integers or floats is easy, but if you try to convert more complex objects, such as human-generated classes, the result may be different from what you expect.

Let’s try the following class:

This class takes two arguments, and the constructor assigns them to the object variables when the object is created.

It’s fine, but when you try to run this code, you will get this result:

You are going to get an object name and its memory address.

To change the default behavior of the string function, you have to overload the str function.

After modification, we have the following code:

After you run this code, the string message is going to be different than the last time.