背景
随便翻《Python基础教程》时,不小心瞥到了repr和str,突然有个问题蹦了出来,repr和str是用来干什么的呢?他们有什么区别呢?
吐槽
首先明白了一点,
他们的作用都是类型转换,即将object转为string。
str
(
object=''
)
repr
(
object
)
Return a string containing a nicely printable representation of an object.
Return a string containing a printable representation of an object.
他们的区别一言以概之,str的目标是可读性,repr的目标是准确性。官网上的说法是
The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval();其中,eval(str [,globals [,locals ]])函数将字符串str当成有效Python表达式来求值,并返回计算结果。
The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval();其中,eval(str [,globals [,locals ]])函数将字符串str当成有效Python表达式来求值,并返回计算结果。
真的是这种区别吗???
实验1:
s='1+2'
print eval(s)
print eval(repr(s))
print eval(str(s))
输出
3
1+2
3
实验2:
class Obj:
def __init__(self):
self.name="xyz"
if __name__ == '__main__':
obj=Obj()
print repr(obj)
print str(obj)
输出:
<__main__.Obj instance at 0x01644A58>
<__main__.Obj instance at 0x01644A58>
实验3:
class Obj:
def __init__(self):
self.name="xyz"
if __name__ == '__main__':
obj=Obj()
print eval(repr(obj))
print eval(str(obj))
输出:
Traceback (most recent call last):
File "E:\webdev\ReprStr\Main.py", line 13, in <module>
print eval(str(obj))#eval(repr(obj))也是一样
File "<string>", line 1
<__main__.Obj instance at 0x017C49B8>
^
SyntaxError: invalid syntax
实验4:
lst=[12,34,5]
print lst==eval(str(lst))
print lst==eval(repr(lst))
输出:
True
True
完全没看到repr存在的意义啊!!!
是我功力不够吗?先留在这,学好了Python再来探究!