Python -- 值轉換爲字符串的兩種機制

能夠經過如下兩個函數來使用這兩種機制:一是經過str函數,它會把值轉換爲合理形式的字符串,以便用戶能夠理解;而repr會建立一個字符串,它以合法的Python表達式的形式來表示值。下面是一些例子:shell

>>> print repr("Hello, world!")
'Hello, world!'
>>> print repr(10000L)
10000L
>>> print str("Hello, world!")
Hello, world!
>>> print str(10000L)
10000

repr(x)的功能也能夠用`x`實現(注意,`是反引號,而不是單引號,在鍵盤tab上面,數字1前面)。若是但願打印一個包含數字的句子,那麼反引號就頗有用了。函數

>>> temp = 42
>>> print "the temperature is " + temp
Traceback (most recent call last):
    File "<pyshell#61>", line 1, in?
        print "the temperature is " + temp
TypeError: cannot add type "int" to string
>>> print "the temperature is " + `temp`
the temperature is 42

注意,在Python3.0 中,已經再也不使用反引號了。所以,即便在舊的代碼中看到了反引號,你也應該堅持使用repr。spa

簡而言之, str、repr和反引號是將Python值轉換爲字符串的3種方法。函數str讓字符串更易於閱讀,而repr(和反引號)則把結果字符串轉換爲合法的Python表達式。code

相關文章
相關標籤/搜索