python基礎教程:print()、str()和repr()的區別
阿新 • • 發佈:2021-07-02
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學習交流群: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去掉了""號,因此最終輸出為'你好'
>>>'你好·你好'
>>>print('你好')
你好
>>>print(str('你好'))
你好
>>>print(repr('你好'))
'你好'
>>>