格式化多行字符串时保留缩进级别

2024-05-23 21:30:08 发布

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

我正在使用Python生成Coffeescript

我有一个模板字符串,如下所示:

format = {
    'start':        '''
                    getEvents = (aic) ->
                      events = {
                    ''',
    'event_start':  '''
                        {event_name}: {
                          precommand: (aic) ->
                            {precommands}
                          postcommand: (aic) ->
                            {postcommands}
                          lines: [
                    ''',
    'event_end':    '''
                          ]
                        }
                    ''',
    'end':          '''
                      }
                    '''
}

Python将非常有帮助地保留这些模板的缩进级别,以生成正确缩进的Coffeescript。但是,当我尝试使用多行格式化这些模板时:

precommands = ["aic.eggs = false", "if aic.ham then spam = true"]
format['event_start'].format(precommands="\n".join(precommands))

我显然得到了一些缩进不正确的东西:

'''
    {event_name}: {
      precommand: (aic) ->
        aic.eggs = false
if aic.ham then spam = true
      postcommand: (aic) ->
        {postcommands}
      lines: [
'''

如何使格式化过程保持缩进级别

类似:Indentation preserving formatting of multiline strings


Tags: nameevent模板formataic级别starteggs