【问题标题】:Why are some Python strings are printed with quotes and some are printed without quotes?为什么有些 Python 字符串打印时带有引号,而有些字符串打印时不带引号?
【发布时间】:2013-06-14 20:17:22
【问题描述】:

我对字符串表示有疑问。我正在尝试打印我的对象,有时我会在输出中得到单引号。请帮助我了解它发生的原因以及如何打印出不带引号的对象。

这是我的代码:

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))

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

【问题讨论】:

  • 好的,我找到了为什么 repr(x) 在引号中产生字符串here

标签: python string representation


【解决方案1】:

字符串上的repr 给出引号,而str 没有。例如:

>>> 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)

改为。

【讨论】:

    猜你喜欢
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-23
    • 2019-09-12
    • 2019-03-01
    • 1970-01-01
    相关资源
    最近更新 更多