In Python, there are usually two ways to convert a variable or constant of a certain type to a string object, namely str () or repr ().
Difference and use
The function str () is used to convert a value into a form suitable for human reading, while REPR () translates into a form for the interpreter to read (SyntaxError exception occurs if there is no equivalent syntax), suitable for use in the development and debugging phases.
>>> number = 123456789>>> type (str (number)) <class ' str ' >>>> type (repr (number)) < Class ' str ' >>>> print (repr (number)) 123456789>>> print (str (number)) 123456789
The two functions return the same type, and the values are the same.
>>> Print (str (' 123456789 ')) 123456789>>> print (repr (' 123456789 ')) ' 123456789 '
But when we pass a string to the Str () function and print it to the terminal, the output character is not quoted. When you pass a string to the repr () function and print it 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 __str__ method that called the object to output the result. The print binding repr () is actually the output of the __repr__ method that invokes the object. 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 (' 123456789 '. __repr__ ()) ' 123456789 ' >>> print (' 123456789 '. __str__ ()) 123456789
Different processing of different data types
If an object does not have an explanatory form suitable for human reading, STR () returns a value equal to repr (). Many types, such as numeric or linked lists, and dictionaries, have a uniform approach to each function.
code example:
>>> ListA = [1,2,3]>>> str (listA) ' [1, 2, 3] ' >>> repr (ListA) ' [1, 2, 3] ' >>>
The result is the same.
Strings and floating-point numbers, however, are handled in different ways.
Note: The Python3 and Python2 versions of the STR function are different when dealing with floating-point numbers, and in the Python3 version, STR and repr return the same results, and the Python2 is not, see the following example:
Python3 version:
>>> string = ' Hello, pythontab.com ' >>> str (string) ' Hello, pythontab.com ' >>> repr (String) ' Hello, pythontab.com ' ">>> str (1.0/7.0) ' 0.14285714285714285 ' >>> repr (1.0/7.0) ' 0.14285714285714285 '
Python2 version:
>>> str (1.0/7.0) ' 0.142857142857 ' >>> repr (1.0/7.0) ' 0.14285714285714285 '
The difference between the Str () and REPR () functions in Python