總的來說
- 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