python基础之%s和%r的区别

在python中,%s和%r的对应调用方法如下,它们都可以用来转换字符串。
%s -> str
%r -> repr
其中,str的可读性强,repr倾向于表明一个对象的详细信息。一般来说,在一个类中,__repr__一般都会又,__str__不一定有,而当__str__()函数没有定义的时候,__repr__定义的话,调用str和repr一样,即是str=repr。
     看下面的例子,
>>> print(repr('hello'))
'hello'
>>>
>>> print(str('hello'))
hello  
>>> print(repr(1))
1
>>> print(str(1))

       str和repr打印字符串的结果是不一样的,那是因为它继承的object.__repr__(self),转换成"正式(official)"字符串(反向引用),而object.__str__(self)是转换成"非正式的(imfomal)", 但是打印int类型的是一样的。

        使用eval()函数可以看出它们区别,repr返回的是有效的字符串,而str返回的是无效的字符串

>>> teststr = 'hello'
>>> repr(teststr)
"'hello'"
>>> str(teststr)
'hello'
>>> teststr2 = eval(repr(teststr))
>>> teststr == teststr2
True
>>>
>>> eval(str(teststr))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'hello' is not defined

     从例子可以看出,再eval()中,把str返回的字符串当成了一个名字是'hello'的未定义变量名,而用repr返回的结果得到的字符串对象teststr2和teststr是同一个对象。

再看看下面的例子,自定义一个类:

# coding=utf-8
class Foo(object):
    def __init__(self, foo):
        self.foo = foo

    def __repr__(self):
        return 'Foo(%r)' % self.foo

    def __str__(self):
        return self.foo

if __name__ == '__main__':
    test = Foo('hello')
    print(test)
    print('test instance,%%r is %r , %%s is %s' % (test, test))

输出结果:

C:\Python36-32\python.exe D:/PythonLearning/PythonCore/test.py
hello
test instance,%r is Foo('hello') , %s is hello

当注释__str__函数后,str和repr的输出结果一样的:

C:\Python36-32\python.exe D:/PythonLearning/PythonCore/test.py
Foo('hello')
test instance,%r is Foo('hello') , %s is Foo('hello')
在上面的基础上注释__repr__函数后,输出结果:
C:\Python36-32\python.exe D:/PythonLearning/PythonCore/test.py
<__main__.Foo object at 0x052A0410>
test instance,%r is <__main__.Foo object at 0x052A0410> , %s is <__main__.Foo object at 0x052A0410>
     总结:str一般用于一个string显示的友好,可以理解成该字符串直接了当的告诉针用户是什么,而repr较为规范的表示string是程序员使用的。

猜你喜欢

转载自blog.csdn.net/mucangmang/article/details/79823583