儘管str(),repr()和``運算在特性和功能方面都很是類似,事實上repr()和``作的是徹底同樣的事情,它們返回的是一個對象的「官方」字符串表示,也就是說絕大多數狀況下能夠經過求值運算(使用內建函數eval())從新獲得該對象,但str()則有所不一樣。str()致力於生成一個對象的可讀性好的字符串表示,它的返回結果一般沒法用於eval()求值,但很適合用於print語句輸出。須要再次提醒的是,並非全部repr()返回的字符串都可以用 eval()內建函數獲得原來的對象。 函數
也就是說 repr() 輸出對 Python比較友好,而str()的輸出對用戶比較友好。雖然如此,不少狀況下這三者的輸出仍然都是徹底同樣的。 spa
>>> s = 'Hello, world.' >>> str(s) 'Hello, world.' >>> repr(s) "'Hello, world.'" >>> str(0.1) '0.1' >>> repr(0.1) '0.10000000000000001' >>> x = 10 * 3.25 >>> y = 200 * 200 >>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...' >>> print s The value of x is 32.5, and y is 40000... >>> # The repr() of a string adds string quotes and backslashes: ... hello = 'hello, world\n' >>> hellos = repr(hello) >>> print hellos 'hello, world\n' >>> # The argument to repr() may be any Python object: ... repr((x, y, ('spam', 'eggs'))) "(32.5, 40000, ('spam', 'eggs'))"