gpt4 book ai didi

python - 为什么有的 Python 字符串打印时带引号,有的打印时不带引号?

转载 作者:太空狗 更新时间:2023-10-29 21:24:35 25 4
gpt4 key购买 nike

我对字符串表示有疑问。我正在尝试打印我的对象,但有时会在输出中出现单引号。请帮助我理解为什么会发生这种情况,以及如何打印出不带引号的对象。

这是我的代码:

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 会给出引号,而 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)

相反。

关于python - 为什么有的 Python 字符串打印时带引号,有的打印时不带引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17171889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com