为什么有些Python字符串用引号打印,而有些不用引号打印? [英] Why are some Python strings are printed with quotes and some are printed without quotes?

查看:1013
本文介绍了为什么有些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.

这是我的代码:

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

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

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

推荐答案

repr给出引号,而str则不给出引号.例如:

repr on a string gives quotes while str does not. 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)

相反.

这篇关于为什么有些Python字符串用引号打印,而有些不用引号打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆