Both these functions are there for getting a string representation of an object in python for data science.
Example of str():
Now let us look at an example of repr():
From looking at the example above we can conclude that repr() prints the string with a pair of quotes. Also repr() gives more accurate value for calculations compared to repr().
- When we want to create output for end users, we use str() but in case of debugging and development repr() is used. The main function of str() is to be readable whereas repr() serves the function of being unambiguous.
- When we use repr(), it computes the ‘official’ string representation of an object but str() computes ‘informal’ string representation. This means repr() provides all the information about the object but str() only provides information which is useful for printing the object.
- In case of print statement and str(), to display the string representation, built-in function uses __str__ but, in case of repr(), __repr__ is used for the representation of the built-in function.
Let us look into an example to clear our concept.
Using str() and repr() for own defined classes:
When there is a need for debugging then, the user-defined class should contain __repr__ function. But if we only need to make it readable for users, we use __str__ function.