为什么有些Python字符串是用引号打印的,有些是用引号打印的?

时间:2013-06-18 14:44:31

标签: python string representation

我遇到字符串表示问题。我正在尝试打印我的对象,有时我会在输出中得到单引号。请帮助我理解它为什么会发生,如何打印出没有引号的对象。

这是我的代码:

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)

以下是我的工作:

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

这是我得到的:

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

这是我想要的:

(X (Y y) (Z z))

为什么引号出现在终端节点的值周围,而不是在非终端的值周围?

1 个答案:

答案 0 :(得分:14)

字符串上的

repr会给出引号,str则不会。 e.g:

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

尝试:

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)

代替。

相关问题