Python 有辦法將任意值轉為字符串:將它傳入repr() 或str() 函數。
函數str() 用於將值轉化為適於人閱讀的形式,而repr() 轉化為供解釋器讀取的形式(如果沒有等價的
語法,則會發生SyntaxError 異常) 某對象沒有適於人閱讀的解釋形式的話, str() 會返回與repr()
等同的值。很多類型,諸如數值或鏈表、字典這樣的結構,針對各函數都有着統一的解讀方式。字符串和
浮點數,有着獨特的解讀方式。
Some examples:
下面有些例子
>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(1.0/7.0)
'0.142857142857'
>>> repr(1.0/7.0)
'0.14285714285714285'
>>> 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'))"