python格式化字符串以忽略缩进空白

2024-09-30 01:35:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个具有实例属性a、b、c的类。我使用了textwarp,但它不起作用。在

 def __str__(self):
    import textwrap.dedent
    return textwrap.dedent(
    """#{0}
    {1}
    {2}
    """.format(self.a,self.b,self.c)

但是,这不起作用,我得到的输出

^{pr2}$

Tags: 实例importselfformatreturn属性defstr
3条回答

textwrap.dedent条带公共前导空格(参见documentation)。如果你想让它起作用,你需要这样做:

def __str__(self):
    S = """\
        #{0}
        {1}
        {2}
    """
    return textwrap.dedent(S.format(self.a, self.b, self.c))

这样做:

from textwrap import dedent

def __str__(self):
    return textwrap.dedent("""\
        #{0}
        {1}
        {2}
        """.format(self.a,self.b,self.c))

当使用"""呈现字符串时,新行和空白都会被计算在内。如果您想让它在没有dedent的情况下工作,您的代码应该如下所示:

def __str__(self):
   return """#{0}
{1}
{2}
""".format(self.a,self.b,self.c)

否则,{1}{2}之前的制表符也在字符串中。或者,您可以使用:

^{pr2}$

关于dedent以及它为什么不工作,请注意documentation中的这一行:

the lines " hello" and "\thello" are considered to have no common leading whitespace.

所以如果你想让dedent工作,你需要每一行的开头都一样,所以你的代码应该是:

    return textwrap.dedent(
    """\
    #{0}
    {1}
    {2}
    """.format(self.a,self.b,self.c))

在这个例子中,每一行都以\t开头,dedent识别并删除。在

相关问题 更多 >

    热门问题