python中的print()、str()和repr()的区别
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                python中的print()、str()和repr()的区别
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                1.定義
- print()函數,生成可讀性更好的輸出, 它會省去引號并打印
- str()函數,用于將值轉化為適于人閱讀的字符串的形式
- repr()函數,用于將值轉化為供解釋器讀取的字符串形式
print()函數,我們可以看出,在Python IDLE中直接輸入的字符串都是有類型的,而print打印后的字符串相當于一串文字,把字符串的引號也省略了,沒有類型
2.實例
>>>123 123 >>> type(123) <class 'int'> >>> print(123) 123 >>> type(print(123)) 123 <class 'NoneType'> >>> '123' '123' >>>type('123') <class 'str'> >>> print('123') 123 >>> type(print( '123')) 123 <class "NoneType '> >>>str()函數,將值轉化成字符串,但是這個字符串是人眼看到的,對人描述的字符串
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' >>>123 123 >>> type(123) <class 'int'> >>> str(123) '123' >>>type(str(123)) <class 'str'> >>> '123' '123' >>>type('123') <class 'str'> >>> str('123') '123' >>>type(str('123')) <class 'str'> >>>那么,python解釋器讀取的字符串又是什么呢?
repr()函數能夠為我們揭曉答案,repr()和str()的區別是,當值為字符串時,str()返回的是字符串本身’123’,而repr()返回的是解釋器讀取的字符串," ‘123’ "
>>>123 123 >>> type(123) <class 'int'> >>> repr(123) '123' >>> type(repr(123)) <class 'str'> >>> '123' '123' >>>type('123') <class 'str '> >>> repr('123') '123' >>> type(repr( '123')) <class 'str'> >>>結合三者,我們看個實例:
- 原字符串輸出是其本身
- 加了print,輸出去掉了’'號
- str(‘你好’)輸出是其本身,加了print,去掉了’'號
- repr(‘你好’)輸出是供解釋器讀取,輸出為" ‘你好’ “,print去掉了”"號,因此最終輸出為’你好’
總結
以上是生活随笔為你收集整理的python中的print()、str()和repr()的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: python中的类和对象
- 下一篇: python基础教程:3种控制流语句(i
