In Python, there are usually two ways to convert a variable or constant of a certain type to a string object, that is, str() or repr() .
>>> a = 10>>> type (str (a))<class'str'>> >> Type (repr (a))<class'str'>
But what's the difference between the two? Because it doesn't make sense to provide two fully functional built-in functions. Let's look at an example first.
Print (Str ('123')) 123 Print(str (123)) 123 print(repr ('123' ) ' 123'print (repr (123)) 123
It is not difficult to see from the example that when we pass a string str() to the function and then print it to the terminal, the output character is not quoted. When a string is passed repr() to the function and then printed to the terminal, the output character is quoted.
The reasons for the differences between the two output modes are:
The print statement, combined with the STR () function, is actually the method that called the object __str__ to output the result. The print binding repr () is actually the method that invokes the object to __repr__ output the result. In the following example, we use the Str object to call these two methods directly, the output of the form is consistent with the previous example.
Print ('123'. __repr__ ())'123'print('123'). __str__())123
However, this example may not be very good at expressing the meaning of Str () and repr (), let's look at an example.
from Import datetime>>> now = DateTime.Now ()print(now)print( Repr (now)) Datetime.datetime (2017, 4, 22, 15, 41, 33, 12917)
With the output of STR () We are well aware of the contents of the now instance, but we have lost the data type information of the then instance. With the output of repr () we can not only get the contents of the now instance, but also know that now is an datetime.datetime instance of the object.
So the difference between STR () and repr () is that:
- The output of STR () is for readability, the output format is easy to understand and is suitable for outputting content to the user terminal.
- REPR () The output of the pursuit of clarity, in addition to object content, but also to show the object's data type information, suitable for the development and debugging phase use.
In addition, if you want instances of your custom class to be called by STR () and repr (), you need to overload and method in your custom class __str__ __repr__ .
The difference between STR () and REPR () functions in Python