2013-04-30 153 views
0

我有一個字符串格式化的小問題。我想用{}替代答案。當我更改答案時,Thing會正確存儲new_answer,但不正確地打印它。它會以某種方式只打印第一個字符!String .format()只返回第一個字符

這是怎麼回事?我真的很迷茫..

class Thing(object): 

    def __init__(self,sentence,answer=None): 
     self.sentence = sentence 
     self.blanks = sentence.count("{}") 
     self.answer = (answer if answer else "___" for i in range(0,self.blanks)) 

    def __str__(self): 
     return self.sentence.format(*self.answer) 

    def changeAnswer(self,new_answer): 
     self.answer = new_answer 

    def returnAnswer(self): 
     return self.answer 

def test(): 
    thang = Thing("Please put it in the {}.") 
    print thang # Please put it in the ___. 
    thang.changeAnswer("BLANK") 
    print thang # Please put it in the B. 
    print thang.returnAnswer() # BLANK 

test() 

回答

3

您使用的發電機當你第一次初始化self.answer,但你在changeAnswer使用的字符串。通過使用參數解包,您可以將字符串生成器解壓爲單個字符串,但最終會將字符串解壓縮爲單個字符。

像這樣的東西應該修復它(即改變changeAnswer):

class Thing(object): 
    def __init__(self, sentence, answer=None): 
     self.sentence = sentence 
     self.num_blanks = sentence.count("{}") 
     self.answer = [answer or "___"] * self.num_blanks 

    def __str__(self): 
     return self.sentence.format(*self.answer) 

    def changeAnswer(self, new_answer): 
     self.answer = [new_answer] * self.num_blanks 

    def returnAnswer(self): 
     return self.answer 

def test(): 
    thang = Thing("Please put it in the {}.") 
    print thang # Please put it in the ___. 
    thang.changeAnswer("BLANK") 
    print thang # Please put it in the B. 
    print thang.returnAnswer() # BLANK 

if __name__ == '__main__': 
    test() 

另外,我會避免像returnAnswer方法。

+0

非常感謝你,這看起來像真正的交易。你能告訴我爲什麼我應該避免returnAnswer(或發送給我的頁面)? – user2245942 2013-04-30 18:52:44

+0

@ user2245942:這是多餘的,並不能真正簡化任何事情。當你可以做'print thang.answer'時,你爲什麼要寫'print thang.returnAnswer()'? – Blender 2013-04-30 18:53:15

相關問題