python中str()和repr()函數的區別


Python 有辦法將任意值轉為字符串:將它傳入repr() 或str() 函數。

    函數str() 用於將值轉化為適於人閱讀的形式,而repr() 轉化為供解釋器讀取的形式。

對於數值類型、列表類型,str和repr方法的處理是一致;而對於字符串類型,str和repr方法處理方式不一樣。

repr()函數得到的字符串通常可以用來重新獲得該對象,repr()的輸入對python比較友好,適合開發和調試階段使用。通常情況下obj==eval(repr(obj))這個等式是成立的。

>>> obj = 'I love Python'
>>> obj = = eval ( repr (obj))
True

 而str()函數沒有這個功能,str()函數適合print()輸出

 1 >>> obj = 'I love Python'
 2 >>> obj==eval(repr(obj))
 3 True
 4 >>> obj == eval(str(obj))
 5 Traceback (most recent call last):
 6   File "<stdin>", line 1, in <module>
 7   File "<string>", line 1
 8     I love Python
 9          ^
10 SyntaxError: invalid syntax

repr()函數(python3中):

1 >>> repr([0,1,2,3])
2 '[0, 1, 2, 3]'
3 >>> repr('Hello')
4 "'Hello'"
5  
6 >>> str(1.0/7.0)
7 '0.14285714285714285'
8 >>> repr(1.0/7.0)
9 '0.14285714285714285'

對比:

1 >>> repr('hello')
2 "'hello'"
3 >>> str('hello')
4 'hello'

對於一般情況:

1 >>> a=test()
2 >>> a
3 <__main__.test object at 0x000001BB1BD228D0>
4 >>> print(a)
5 <__main__.test object at 0x000001BB1BD228D0>
6 >>> 

不管我們是輸入對象還是print(對象),返回的都是對象的內存地址
對於方法__str__:

 1 >>> class test():
 2     def __str__(self):
 3         return "你好"
 4 
 5     
 6 >>> a=test()
 7 >>> a
 8 <__main__.test object at 0x000001BB1BD22860>
 9 >>> print(a)
10 你好
11 >>> 

如果我們在終端中輸入對象,會返回對象的內存地址,使用print則會自動調用方法__str__
對於方法__repr__:

 1 >>> class test():
 2     def __repr__(self):
 3         return "你好"
 4 
 5 >>> a=test()
 6 >>> a
 7 你好
 8 >>> print(a)
 9 你好
10 >>> 

如果我們在終端中輸入對象,使用print都會自動調用方法__repr__
通常,程序員會在開發時,使用__repr__來返回一些關鍵性的信息便於調試。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM