【问题标题】:python formatting strings to ignore indentation whitespacepython格式化字符串以忽略缩进空格
【发布时间】:2014-10-24 13:13:21
【问题描述】:

我有一个具有实例属性 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

【问题讨论】:

  • textwrap.dedent 去掉了常见的前导空格。这意味着每行前面必须有相同的空格。显然,您的第一行 "#{0}... 没有。

标签: python string formatting


【解决方案1】:

这样做:

from textwrap import dedent

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

【讨论】:

    【解决方案2】:

    当您使用""" 渲染字符串时,换行符和空格都会被计算在内。如果您希望它在没有 dedent 的情况下工作,您的代码应如下所示:

    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 及其不工作的原因,请注意 documentation 中的这一行:

    “hello”和“\thello”这行被认为没有共同的前导空格。

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

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

    在这种情况下,每一行都以\t 开头,dedent 可以识别并删除它。

    【讨论】:

      【解决方案3】:

      textwrap.dedent 去除常见的前导空格(参见documentation)。如果你想让它工作,你需要做这样的事情:

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

      【讨论】:

      • 谢谢。我完全错过了。
      猜你喜欢
      • 1970-01-01
      • 2015-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-16
      • 2015-02-18
      • 1970-01-01
      相关资源
      最近更新 更多