repr与str的区别

nasta posted @ 2013年10月11日 16:07 in Code with tags Python , 1674 阅读

help(repr):

repr(...)
    repr(object) -> string
    
    Return the canonical string representation of the object.
    For most object types, eval(repr(object)) == object.

返回对象的典型表示形式(Python解释器所能理解的),后面一句非常重要,对于大多数类型eval(repr(object)) == object

 

help(str):

class str(basestring)
 |  str(object) -> string
 |  
 |  Return a nice string representation of the object.
 |  If the argument is a string, the return value is the same object.

返回对象的字符串表示(能打印出的人们能理解的)

 

这样一来,就很好区别了。再来两个例子:

>>> s = "this is a string"
>>> str(s)
'this is a string'
>>> repr(s)
"'this is a string'"

>>> l = [ "l", "i", "s", "t" ]
>>> str(l)
"['l', 'i', 's', 't']"
>>> repr(l)
"['l', 'i', 's', 't']"

 


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter