str() vs. repr() :-

Both these functions are there for getting a string representation of an object in python for data science.

Example of str():

python data science

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().

Major Differences:

  • 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.

python data science

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.

If you want to learn more about str and repr functions in detail with related to python for data science then you can check this and this as well.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.