Обрезать строку от символа A до символа B

Я читаю файл, содержание которого примерно следующее:

block1:
   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla consequat ante nisi, id 
   vestibulum felis tempor ac. Ut semper, ligula id sollicitudin efficitur, nisl diam elementum 
   lectus, nec iaculis turpis felis non mauris. Aenean elementum tortor a tristique iaculis. Morbi 
   a aliquam diam. Donec blandit orci sit amet ante hendrerit sodales.
block2:
   <h1> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla consequat ante nisi, id 
   vestibulum felis tempor ac. Ut semper, ligula id sollicitudin efficitur, nisl diam elementum 
   lectus, nec iaculis turpis felis non mauris. Aenean elementum tortor a tristique iaculis. Morbi 
   a aliquam diam. Donec blandit orci sit amet ante hendrerit sodales. Morbi quis quam quis augue 
   fermentum tempus ac a ante. In vel dui interdum turpis sodales tincidunt. Praesent eget maximus 
   lorem. Phasellus mollis gravida nisi vitae pellentesque. Curabitur sed felis eget quam 
   tincidunt malesuada. </h1>

Необходимо получить содержимое каждого блока, я пробовал следующий код:

f = open("filename.txt")
fcontent = f.read()
f.close()

contents = []
block_names = ("block1", "block2")

positions = len(block_names)
for pos in range(positions):
    current_block = block_names[pos]
    next_block = block_names[pos + 1]

    contents.append(
        fcontent[fcontent.find(current_block)] + len(current_block) + 1: next_block]
    )

Ответы (2 шт):

Автор решения: CrazyElf

Немного переделал, так в общем работает:

block_names = ("block1", "block2")
positions = [fcontent.find(bn) for bn in block_names]
contents = [fcontent[pos1+len(bn)+1:pos2] for bn, pos1, pos2 in zip(block_names, positions, positions[1:]+[None])]

У вас сразу несколько ошибок было:

  • квадратная скобка не там закрыта
  • вместо конечной позиции среза было название блока
  • ну и такой метод перебора не позволял захватить последний блок
→ Ссылка
Автор решения: StupidNoob

Написал код, который способен решить данную задачу:

word_key = '<--block-->'


def fiend_block(content=[]):
    numb = []
    for el in range(len(content)):
        if word_key in content[el]:
            numb.append(el)
    return numb


if __name__ == '__main__':
    with open('2.txt') as file:
        content_list = file.readlines()
    a = fiend_block(content_list)
    _list = []

    for numb in range(len(a)):
        sls = str()
        if not a[numb] == a[-1]:
            for el in content_list[a[numb]:a[numb+1]]:
                if not word_key in el:
                    sls += el
        else:
            for el in content_list[a[numb]:-1]:
                if not word_key in el:
                    sls += el
        _list.append(sls)

Но теперь каждый блок (block1:, block2:) должен называться, как вы укажите в word_key и он не должен использоваться в тексте. Файл:введите сюда описание изображения

Результат выполнения print(_list[0]):введите сюда описание изображения

→ Ссылка