str() Vs repr() in Python
In this Python tutorial we will learn str() Vs repr() in Python, which means the difference between str() and repr().
In Python, strings are one of the basic data types. It includes any characters altogether placed between single(‘ ‘) or double (” “) quotes. It has many built-in methods and functions through various operations that can be performed on a particular string.
These functions or methods can be displayed with their use by typing
in the Python IDLE.
The functions str() and repr() are some of the built-in functions. Both these functions have an argument within the parenthesis otherwise, the function will not give any results. These functions perform the function of typecasting an object. Typecasting an object is nothing but changing the type of an object.
For the above functions, they are used to typecast the argument to string data-type. Both of these functions perform the same function however in very different ways.
Difference between str() and repr() in Python with example program
a="hello" s=str(a) r=repr(a) print(a) print(r)
So, it can be noted that the string in s is only enclosed in the single quotes but the string in r is enclosed in the single quotes as well as an extra pair of double-quotes ( You may learn: how to escape quotes in python ). This difference can only be noted if you input a string datatype in the variable a.
Thus, it can be inferred that str() is used for creating output for user while repr() is mainly used for debugging and development. repr’s goal is to be unambiguous and str’s is to be readable
For eg: if division is carried out and the quotient turns to be a decimal, str() may round it off but repr() would display the precise result without rounding off.
Thus we can also say repr() gives a more official representation and represents the actual information to be stored, irrespective of the fact that it is readable or not. Also, the computation time of the repr() command is O(n**2) while the time complexity of str() is O(n). Here, n is the length of string or the object.