Вместо того, чтобы использовать регулярное выражение или полагаться на определенное форматирование, вы можете использовать модуль токена python.
import tokenize
f=open(filename)
insert_index = None
for tok, text, (srow, scol), (erow,ecol), l in tokenize.generate_tokens(f.readline):
if tok == tokenize.COMMENT:
continue
elif tok == tokenize.STRING:
insert_index = erow, ecol
break
else:
break # No docstring found
Таким образом, вы можете справиться даже с такими патологическими случаями, как:
# Comment
# """Not the real docstring"""
' this is the module\'s \
docstring, containing:\
""" and having code on the same line following it:'; this_is_code=42
Точно так же, как Python будет обрабатывать их.