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


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

>>> 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。

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM