【Python】Python中str()和repr()函数的区别
作用
在 Python 中要將某一類型的變量或者常量轉換為字符串對象通常有兩種方法,即 str() 或者 repr() 。
區別與使用
參考文章:Python 中 str() 和 repr() 函數的區別
函數 str() 用于將值轉化為適于人閱讀的形式,而 repr() 轉化為供解釋器讀取的形式(如果沒有等價的語法,則會發生 SyntaxError 異常), 適合開發和調試階段使用。
>>> number = 123456789 >>> type(str(number)) <class 'str'> >>> type(repr(number)) <class 'str'> >>> print(repr(number)) 123456789 >>> print(str(number)) 123456789兩個函數返回的類型是相同的,值也是相同的。
>>> print(str('123456789')) 123456789 >>> print(repr('123456789')) '123456789'但當我們把一個字符串傳給 str() 函數再打印到終端的時候,輸出的字符不帶引號。而將一個字符串傳給 repr() 函數再打印到終端的時候,輸出的字符帶有引號。
造成這兩種輸出形式不同的原因在于:
print 語句結合 str() 函數實際上是調用了對象的 __str__ 方法來輸出結果。而 print 結合 repr() 實際上是調用對象的 __repr__ 方法輸出結果。下例中我們用 str 對象直接調用這兩個方法,輸出結果的形式與前一個例子保持一致。
>>> print('123456789'.__repr__()) '123456789' >>> print('123456789'.__str__()) 123456789實戰:自定義類的 str() 與 repr()
示例 1:僅在類中聲明__str__方法
自定義類如下:
class ValueTime:value = -1time = ''def __init__(self, value, time):self.value = valueself.time = timedef __str__(self):return "ValueTime:value={}, time={}".format(self.value, self.time)輸出由ValueTime組成的list組成的list(list嵌套),實際輸出的是對象的類名,并沒有調用到自定義的__str__方法。
[[<app.models.ValueTime instance at 0x0000000003E02AC8>, <app.models.ValueTime instance at 0x0000000003E02B08>, <app.models.ValueTime instance at 0x0000000003E02B48>, …], […], […], …]
示例 2:在類中聲明__repr__方法與__str__方法
自定義類如下:
class ValueTime:value = -1time = ''def __init__(self, value, time):self.value = valueself.time = timedef __str__(self):return "ValueTime:value={}, time={}".format(self.value, self.time)def __repr__(self):return "ValueTime:value={}, time={}".format(self.value, self.time)輸出由ValueTime組成的list組成的list(list嵌套),可以輸出自定義格式化的對象,此時調用到了自定義的__repr__方法。
[[ValueTime:value=22, time=2009-03-27, ValueTime:value=11, time=2009-03-30, ValueTime:value=22, time=2009-03-31, ValueTime:value=33, time=2009-04-01], […], […], …]
總結
以上是生活随笔為你收集整理的【Python】Python中str()和repr()函数的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Python】zip函数的使用
- 下一篇: 【Python】吐槽SQLAlchemy