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()
非常感謝你,這看起來像真正的交易。你能告訴我爲什麼我應該避免returnAnswer(或發送給我的頁面)? – user2245942 2013-04-30 18:52:44
@ user2245942:這是多餘的,並不能真正簡化任何事情。當你可以做'print thang.answer'時,你爲什麼要寫'print thang.returnAnswer()'? – Blender 2013-04-30 18:53:15