python 中的str和repr

str(obj)函数返回字符串本身
而repr(obj)函数,返回的是obj这个变量在解释器中,真实存在的样子
 
python2环境:
>>> s = ''
>>> print s
张
>>> print repr(s)
'\xd5\xc5'
>>> print str(s)
张



>>> str('zhang')
'zhang'
>>> repr('zhang')
"'zhang'"

 

python3环境:

>>> s=''
>>> print(str(s))
张
>>> print(repr(s))
''


>>> str('zhang')
'zhang'
>>> repr('zhang')
"'zhang'"           

 

 

再来看一看对象

 

python2:

>>> class Obj(object):
...     def __repr__(self):
...         return 'repr'
...
>>> f1 = Obj()
>>> f1
repr
>>> print(f1)
repr
>>> str(f1)
'repr'
>>> repr(f1)
'repr'


>>> class Obj2(object):
...     def __str__(self):
...         return 'repr'
...
>>> f2 = Obj2()
>>> f2
<__main__.Obj2 object at 0x00000000033FBC18>
>>> print(f2)
repr
>>> str(f2)
'repr'
>>> repr(f2)
'<__main__.Obj2 object at 0x00000000033FBC18>'

 

python3:

>>> class Obj(object):
    def __repr__(self):
        return 'repr'

    
>>> f1=Obj()
>>> f1
repr
>>> print(f1)
repr
>>> str(f1)
'repr'
>>> repr(f1)
'repr'
>>> class Obj2(object):
    def __str__(self):
        return 'repr'

    
>>> f2=Obj2()
>>> f2
<__main__.Obj2 object at 0x0000000002FF3F98>
>>> print(f2)
repr
>>> str(f2)
'repr'
>>> repr(f2)
'<__main__.Obj2 object at 0x0000000002FF3F98>'

 

posted @ 2017-11-20 19:43  张璨  阅读(106)  评论(0编辑  收藏  举报