为什么有些Python字符串是用引号打印的,有些是不带引号打印的?
我对字符串表示有问题。我试图打印我的对象,有时输出中会出现单引号。请帮助我理解为什么会发生这种情况,以及如何打印出没有引号的对象 这是我的密码:为什么有些Python字符串是用引号打印的,有些是不带引号打印的?,python,string,representation,Python,String,Representation,我对字符串表示有问题。我试图打印我的对象,有时输出中会出现单引号。请帮助我理解为什么会发生这种情况,以及如何打印出没有引号的对象 这是我的密码: class Tree: def __init__(self, value, *children): self.value = value self.children = list(children) self.marker = "" def __repr__(self):
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
没有。e、 g:
>>> s = 'foo'
>>> print str(s)
foo
>>> print repr(s)
'foo'
尝试:
相反。好的,我找到了repr(x)在引号中生成字符串的解释
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)