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

2 投票
3 回答
2132 浏览
提问于 2025-04-29 11:32

我有一个类,里面有一些实例属性,分别是a、b和c。我尝试使用textwrap这个工具,但它没有效果。

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

不过,这个方法并没有奏效,我得到的输出是这样的:

a
        b
        c
暂无标签

3 个回答

0

textwrap.dedent 是一个可以去掉文本中共同的前导空白字符的工具(具体可以查看文档)。如果你想让这个功能正常工作,你需要像下面这样做:

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

这样做:

from textwrap import dedent

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

当你用 """ 来显示一个字符串时,换行符和空格都会被计算在内。如果你想让这个功能正常工作而不使用去缩进,代码应该像这样:

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

否则,在 {1}{2} 前面的制表符也会被包含在字符串里。另一种选择是使用:

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

关于去缩进(dedent)以及为什么它不起作用,注意这段来自文档的内容:

像 " hello" 和 "\thello" 这样的行被认为没有共同的前导空格。

所以如果你想让去缩进正常工作,你需要每一行的开头都一致,因此你的代码应该是:

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

在这种情况下,每一行都以 \t 开头,这样 dedent 就能识别并去掉它。

撰写回答