標籤:
repr是對python解譯器友好的,就是會以合法的python運算式的形式來表示值,返回一個可以用來表示對象的可列印字串。
官方解釋:
Python 手冊:
Return a string containing a printable representation of an object.
返回一個用來表示可列印對象的字串。
This is the same value yielded by conversions (reverse quotes).
這是一個通過轉換產生的字串值(並且這個值是引用雙引號的)。
It is sometimes useful to be able to access this operation as an ordinary function.
有時它很有用,能夠作為一個普通函數來操作。
For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(),
對於很多類型,這個函數首先會嘗試返回一個字串值,並且把這個字串值傳給eval()方法時它將產生帶有同樣值的python對象(也就是說,obj=eval(repr(obj)))。
otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object.
否則產生用角括弧包住的字串,包含這個對象的類型名和一些額外的資訊(比如這個對象的地址)。
A class can control what this function returns for its instances by defining a repr() method.
一個類可以通過定義repr()方法,來控制這個類執行個體通過這個函數的傳回值。(這句翻譯有點晦澀,我的瞭解就是,就相當於java裡面定義的tostring()方法,一個類的執行個體對象,如果想轉化為字串形式,這個類就必須定義或者說重寫repr()方法)
(特別指明,別人的解釋是:一個類(class)可以通過 __repr__() 成員來控制repr()函數作用在其執行個體上時的行為。由於剛剛學習python,對於__repr__()我還不是很清楚,後面需要進一步理解)
str是對方便使用的,返回一個可以用來表示對象的可列印的友好的字串
Python 手冊:
Return a string containing a nicely printable representation of an object.
返回一個表示對象的可列印的友好的字串值。
For strings, this returns the string itself.
對於字串類型,通過這個函數返回它本身。
The difference withrepr(object) is that str(object) does not always attempt to return a string that is acceptable to eval();
不同於repr()函數的是這個函數經常不會嘗試返回一個可以傳遞給eval()函數的字串(也就是會報錯:NameError: name ‘xxx‘ is not defined,不是標準字串形式,eval函數會把它當成未定義變數)。
its goal is to return a printable string.
這個函數的目標是返回可以答應的字串,就是對使用者看著比較友好的。
If no argument is given, returns the empty string, .
如果沒有給這個函數傳入參數的話,返回一個Null 字元串。
>>> repr(100)‘100‘>>> str(100)‘100‘>>> repr("aaa")"‘aaa‘">>> str("aaaa")‘aaaa‘>>> print(repr(1000))1000>>> print(str(1000))1000>>> print(repr("bbbbb"))‘bbbbb‘>>> print(str("bbbb"))bbbb
從上面執行的結果,可以看出來,這兩個函數返回的本身都是字串。再進行列印時可以看出,str返回的是對使用者更友好的字串,但是repr返回的呢則依舊是符合python運算式規則的字串表達形式。
=========================未完待續....
repr() VS str()區別