python print用法可以不加引号吗,为什么有些Python字符串用引号打印,而有些不用引号打印?...

I have a problem with string representations. I am trying to print my object and I sometimes get single quotes in the output. Please help me to understand why it happens and how can I print out the object without quotes.

Here is my code:

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)

Here is what I do:

from Tree import Tree

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

print t

Here is what I get:

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

Here is what I want to get:

(X (Y y) (Z z))

Why do the quotes appear around the values of terminal nodes, but not around the values of non-terminals?

解决方案

repr on a string gives quotes while str does not. e.g.:

>>> s = 'foo'

>>> print str(s)

foo

>>> print repr(s)

'foo'

Try:

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)

instead.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值