Python docx Replace string in paragraph while keeping style
<p>I need help replacing a string in a word document while keeping the formatting of the entire document.</p>

<p>I'm using python-docx, after reading the documentation, it works with entire paragraphs, so I loose formatting like words that are in bold or italics.
Including the text to replace is in bold, and I would like to keep it that way.
I'm using this code:</p>

<pre><code>from docx import Document
def replace_string2(filename):
    doc = Document(filename)
    for p in doc.paragraphs:
        if 'Text to find and replace' in p.text:
            print 'SEARCH FOUND!!'
            text = p.text.replace('Text to find and replace', 'new text')
            style = p.style
            p.text = text
            p.style = style
    # doc.save(filename)
    doc.save('test.docx')
    return 1
</code></pre>

<p>So if I implement it and want something like (the paragraph containing the string to be replaced loses its formatting):</p>

<p>This is <strong>paragraph 1</strong>, and this is a text in <strong>bold</strong>.</p>

<p>This is <strong>paragraph 2</strong>, and I will replace <strong>old text</strong></p>

<p>The current result is:</p>

<p>This is <strong>paragraph 1</strong>, and this is a text in <strong>bold</strong>.</p>

<p>This is paragraph 2, and I will replace new text</p>