通過實例了解Python str()和repr()的區(qū)別
這篇文章主要介紹了通過實例了解Python str()和repr()的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
區(qū)別
其實用處就是最大的區(qū)別了:str()主要用來為終端用戶輸出一些信息,而repr()主要用來調(diào)試;同時后者的目標(biāo)是為了消除一些歧義(例如浮點數(shù)的精度問題),前者主要為了可讀。
使用
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'
仔細(xì)看一下,其實并沒產(chǎn)生精度上的不同;但是當(dāng)在Python2中就會發(fā)現(xiàn)區(qū)別了:
>>> eval('2.0/11')
0.18181818181818182
>>> print(2.0/11)
0.181818181818
所以換個例子:
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)'
可以看到前者可讀性更好,后者打印出來了類型和值,更適合調(diào)試;
實現(xiàn)
二者都通過內(nèi)置函數(shù)實現(xiàn);看看官方文檔說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.
意味著可以自定義這個函數(shù),并實現(xiàn)自己的repr()(str同理),如下:
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'
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
利用python在Word文檔中創(chuàng)建和執(zhí)行條件郵件合并
郵件合并域和IF域是Word文檔中兩種非常實用的域,前者可以用來進(jìn)行郵件合并,根據(jù)數(shù)據(jù)批量創(chuàng)建定制的Word文檔,本文講介紹如何使用Python在Word文檔中創(chuàng)建條件郵件合并域以及執(zhí)行條件郵件合并,需要的朋友可以參考下2024-08-08
關(guān)于DataFrame數(shù)據(jù)的查詢和編輯
在使用pandas處理DataFrame時,可通過列索引標(biāo)簽獲取列數(shù)據(jù),行數(shù)據(jù)的獲取可以利用行索引或位置切片,如iloc和loc方法,增加數(shù)據(jù)時,可通過append方法增加行,直接賦值增加列,刪除數(shù)據(jù)則通過drop方法,通過設(shè)置axis參數(shù)確定是刪除行還是列2024-09-09

