该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
纠结了两天,没搞明白str()和erpr()的区别,
官方的解释是这样的:
The str() function is meant to return representations of values which are fairly
human-readable, while repr() is meant to generate representations which can be read by
the interpreter (or will force a SyntaxError if there is not equivalent syntax). For
objects which don't have a particular representation for human consumption, str() will
return the same value as repr(). Many values, such as numbers or structures like lists
and dictionaries, have the same representation using either function. Strings and
floating point numbers, in particular, have two distinct representations.
翻译过来就是:
str()一般是将数值转成字符串。
repr()是将一个对象转成字符串显示,注意只是显示用,有些对象转成字符串没有直接的意思。如list,dict使用str()是无效的,但使用repr可以,这是为了看它们都有哪些值,为了显示之用。
我尝试了一下str(['1','2'])
结果是可以打印出:"['1', '2']"
但是用repr()可以得出想通的区别,
试验了一下eval(repr(list)) 按照希望得到了原来的LIST,又想把str(list) ,发现变不回去了,难道这就是区别???
还有:
a='hello'
str(a) 显示'hello' len一下是5
但是
repr(a) 显示“‘hello'" len下是7 还是没看明白区别是什么…………