print (str("hello"))
輸出爲
hello
print (repr("hello"))
輸出爲
'hello'
這兩者之間有什麼區別呢?
str()一般是將數值轉成字符串。
repr()是將一個對象轉成字符串顯示,注意只是顯示用,有些對象轉成字符串沒有直接的意思。如list,dict使用str()是無效的,但使用repr可以,這是爲了看它們都有哪些值,爲了顯示之用。
Some examples:
>>> 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'))"
>>> # reverse quotes are convenient in interactive sessions:
... `x, y, ('spam', 'eggs')`
"(32.5, 40000, ('spam', 'eggs'))"
提示技巧:在提示符後直接輸入一個變量名print (s),結果跟print (repr(s))是一樣的。
或者直接輸入變量名字:s、 (s) 、x、 y都可以顯示它的值的 。
但是(區別是)直接輸入是(返回)它的值,用print語句打印是(打印)它的值,這兩者之間是有差別的。