多行字符串的缩进保留格式

多行字符串的缩进保留格式

问题描述:

我使用诸如这样的格式字符串生成(C ++)代码的一部分

I generate bits of (C++) code using format strings such as

memfn_declaration = '''\
  {doc}
  {static}auto {fun}({formals}){const}
    -> {result};
'''

格式字符串对此很有用,但是有没有办法使它们在这里保持{doc}的缩进级别呢?通常是多行.

Format strings are nice for this, but is there a way to make them keep the indentation level for {doc} here? It's typically multiline.

我知道我可以将与doc对应的字符串缩进两个空格,我知道有很多功能可以达到这个目的,但这不是我要的:我正在寻找不需要调整我传递的字符串.

I know I can just indent the string corresponding to doc by two spaces, I know there are plenty of functions to this end, but that's not what I'm asking: I'm looking for something that would work without tweaking the strings I pass.

现在,您已经发布了自己的答案,并进一步澄清了所需的内容.我认为通过定义自己的str子类来实现它会稍微好一点,该子类通过支持新的转换类型'i'扩展了格式化字符串的方式,该类型必须紧跟表示缩进级别的十进制数字

Now that you've posted your own answer and clarified at little more about what you want. I think it would be slightly better to implement it by defining your own str subclass that extends the way strings can be formatted by supporting a new conversion type, 'i', which must be followed by a decimal number representing the level of indentation desired.

这是在Python 2及更高版本中均可使用的实现3:

Here's an implementation that works in both Python 2 & 3:

import re
from textwrap import dedent
try:
    from textwrap import indent
except ImportError:
    def indent(s, prefix):
        return prefix + prefix.join(s.splitlines(True))

class Indentable(str):
    indent_format_spec = re.compile(r'''i([0-9]+)''')

    def __format__(self, format_spec):
        matches = self.indent_format_spec.search(format_spec)
        if matches:
            level = int(matches.group(1))
            first, sep, text = dedent(self).strip().partition('\n')
            return first + sep + indent(text, ' ' * level)

        return super(Indentable, self).__format__(format_spec)

sample_format_string = '''\
  {doc:i2}
  {static}auto {fun}({formals}){const}
    -> {result};
'''

specs = {
    'doc': Indentable('''
        // Convert a string to a float.
        // Quite obsolete.
        // Use something better instead.
    '''),
    'static': '',
    'fun': 'atof',
    'formals': 'const char*',
    'const': '',
    'result': 'float',
}

print(sample_format_string.format(**specs))

输出:

  // Convert a string to a float.
  // Quite obsolete.
  // Use something better instead.
  auto atof(const char*)
    -> float;