Python - repr()、str() 的區別


總的來說

  • str():將傳入的值轉換為適合人閱讀的字符串形式
  • repr():將傳入的值轉換為 Python 解釋器可讀取的字符串形式

 

傳入整型

# number
resp = str(1)
print(resp, type(resp), len(resp))
resp = str(1.1)
print(resp, type(resp), len(resp))

resp = repr(1)
print(resp, type(resp), len(resp))
resp = repr(1.1)
print(resp, type(resp), len(resp))


# 輸出結果
1 <class 'str'> 1
1.1 <class 'str'> 3
1 <class 'str'> 1
1.1 <class 'str'> 3

 

傳入字符串

# string
resp = str("test")
print(resp, type(resp), len(resp))

resp = repr("test")
print(resp, type(resp), len(resp))


# 輸出結果
test <class 'str'> 4
'test' <class 'str'> 6

repr() 會在原來的字符串上面加單引號,所以字符串長度會 +2

 


免責聲明!

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



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