區別python
其實用處就是最大的區別了:str()主要用來爲終端用戶輸出一些信息,而repr()主要用來調試;同時後者的目標是爲了消除一些歧義(例如浮點數的精度問題),前者主要爲了可讀。
使用函數
In [12]: s = 'abc' In [13]: print(str(s)) abc In [14]: print(2.0/11) 0.18181818181818182 In [15]: repr(s) Out[15]: "'abc'" In [16]: repr(2.0/11) Out[16]: '0.18181818181818182'
仔細看一下,其實並沒產生精度上的不一樣;可是當在Python2中就會發現區別了:學習
>>> eval('2.0/11') 0.18181818181818182 >>> print(2.0/11) 0.181818181818
因此換個例子:this
#Python學習交流羣:778463939 In [17]: import datetime In [18]: n = datetime.datetime.now() In [19]: print(str(n) ...: ) 2020-01-16 09:22:13.361995 In [20]: repr(n) Out[20]: 'datetime.datetime(2020, 1, 16, 9, 22, 13, 361995)'
能夠看到前者可讀性更好,後者打印出來了類型和值,更適合調試;調試
實現code
兩者都經過內置函數實現;看看官方文檔說repr()文檔
Return a string containing a printable representation of an object. A class can control what this function returns for its instances by defining a __repr__() method.
意味着能夠自定義這個函數,並實現本身的repr()(str同理),以下:string
In [35]: class TestClass: ...: def __init__(self, name, age): ...: self.name = name ...: self.age = age ...: def __repr__(self): ...: return 'repr: ' + self.name + ' ,' + self.age ...: def __str__(self): ...: return self.name + ' ,' + self.age ...: In [38]: tt = TestClass('tony', '23') In [39]: repr(tt) Out[39]: 'repr: tony ,23' In [40]: str(tt) Out[40]: 'tony ,23'