2013-06-18 17 views
7

Mam problem z reprezentacjami ciągów. Próbuję wydrukować mój obiekt i czasami otrzymuję pojedyncze cudzysłowy na wyjściu. Pomóż mi zrozumieć, dlaczego tak się dzieje i jak mogę wydrukować obiekt bez cytatów.Dlaczego niektóre napisy w języku Python są drukowane z cudzysłowami, a niektóre drukowane są bez cudzysłowów?

Oto mój kod:

class Tree: 
    def __init__(self, value, *children): 
     self.value = value 
     self.children = list(children) 
     self.marker = "" 

    def __repr__(self): 
     if len(self.children) == 0: 
      return '%s' %self.value 
     else: 
      childrenStr = ' '.join(map(repr, self.children)) 
      return '(%s %s)' % (self.value, childrenStr) 

Oto co mam zrobić:

from Tree import Tree 
t = Tree('X', Tree('Y','y'), Tree('Z', 'z')) 
print t 

Oto co mam:

(X (Y 'y') (Z 'z')) 

Oto, co chcę dostać:

(X (Y y) (Z z)) 

Dlaczego cytaty pojawiają się wokół wartości węzłów końcowych, ale nie wokół wartości nie-terminali?

+0

OK, znalazłem wyjaśnienie, dlaczego repr (x) tworzy ciągi w cudzysłowach [tutaj] (http://stackoverflow.com/questions/7784148/understanding-repr-function-in-python) – Olga

Odpowiedz

14

repr na łańcuchu podaje cytaty, a str nie. np .:

>>> s = 'foo' 
>>> print str(s) 
foo 
>>> print repr(s) 
'foo' 

Spróbuj:

def __repr__(self): 
    if len(self.children) == 0: 
     return '%s' %self.value 
    else: 
     childrenStr = ' '.join(map(str, self.children)) #str, not repr! 
     return '(%s %s)' % (self.value, childrenStr) 

zamiast.

+0

To działa dla mnie. – Olga

Powiązane problemy