2017-04-26 142 views
0

我想知道,因爲我還沒有找到一個工作的答案,將數據類型轉換爲可讀格式。如何將數據類型轉換爲可讀的字符串

+1

定義「可讀」或者你只是想任何類型轉換爲字符串?如果是這樣,那麼'str(...)'可能就足夠了。 – Vallentin

+2

請閱讀此[如何問](http://stackoverflow.com/help/how-to-ask)以改善您的問題。 – thewaywewere

回答

0

你應該看看添加海峽再版方法,您的數據類型。

str

由STR(被叫)內置函數和print語句 計算對象的「非正式」的字符串表示。

repr

由再版(被叫)內置函數和由字符串轉換 (反向引號)來計算 對象的「正式」的字符串表示。如果可能的話,這應該看起來像一個有效的Python 表達式,它可以用來重新創建一個具有相同 值的對象(給定一個適當的環境)。

例如:

class Car(object): 
    def __init__(self, manufacturer, model): 
     self.manufacturer = manufacturer 
     self.model = model 
    def __str__(self): 
     return self.manufacturer+" "+self.model 
    def __repr__(self): 
     return '{"manufacturer": "'+self.manufacturer+'", "model": "'+self.model+'"}' 

c = Car("Ford", "Focus") 
print str(c) 
> "Ford Focus" 
print repr(c) 
> {"manufacturer": "Ford", "model": "Focus"} 
相關問題