Difference in python str () and the repr () function

Python has a way to any value to a string: pass it to repr () or str () function.

    Str () function is used to translate the value suitable for human readable form, and the repr () for conversion to form read by the interpreter.

For numeric type, list type, str and repr processing method is the same; for string types, str and repr method for processing a different way.

repr () function to get the string can often be used to retrieve the object, repr () input for python more friendly for development and debugging phase of use. Typically obj == eval (repr (obj)) this equation is established.

>>> obj = 'I love Python'
>>> obj = = eval ( repr (obj))
True

 And str () function does this function, str () function for print () output

 1 >>> obj = 'I love Python'
 2 >>> obj==eval(repr(obj))
 3 True
 4 >>> obj == eval(str(obj))
 5 Traceback (most recent call last):
 6   File "<stdin>", line 1, in <module>
 7   File "<string>", line 1
 8     I love Python
 9          ^
10 SyntaxError: invalid syntax

the repr () function (to python3) is:

1 >>> repr([0,1,2,3])
2 '[0, 1, 2, 3]'
3 >>> repr('Hello')
4 "'Hello'"
5  
6 >>> str(1.0/7.0)
7 '0.14285714285714285'
8 >>> repr(1.0/7.0)
9 '0.14285714285714285'

Compared:

1 >>> repr('hello')
2 "'hello'"
3 >>> str('hello')
4 'hello'

For the general case:

1 >>> a=test()
2 >>> a
3 <__main__.test object at 0x000001BB1BD228D0>
4 >>> print(a)
5 <__main__.test object at 0x000001BB1BD228D0>
6 >>> 

Memory address input object or whether we print (Object), returns are subject
to the method __str__:

 1 >>> class test():
 2     def __str__(self):
 3         return "你好"
 4 
 5     
 6 >>> a=test()
 7 >>> a
 8 <__main__.test object at 0x000001BB1BD22860>
 9 >>> print(a)
10 你好
11 >>> 

If we are in a terminal input object, the object will return memory address, use the print will automatically call the method __str__
the method __repr__:

. 1 >>> class Test ():
 2      DEF  __repr__ (Self):
 . 3          return  " hello " 
. 4  
. 5 >>> A = Test ()
 . 6 >>> A
 . 7  hello
 . 8 >>> Print (A)
 . 9  you good
 10 >>>

If we enter an object in a terminal, use the print will automatically call the method __repr__
Typically, programmers in the development, use __repr__ to return some of the key information easy to debug.

Guess you like

Origin www.cnblogs.com/bbzqz/p/11845195.html