'Docx - Replace element and set font-style?

i want to replace some paragraph-text in this docx-file:

enter image description here

This works generally fine using this code:

from docx import Document
from docx.shared import Pt
file = "template.docx"
doc = Document(file)  
for idxPara, elemPara in enumerate(doc.paragraphs):
  if "«Kunde»" in elemPara.text:
    doc.paragraphs[idxPara].text = "Anderer Text für Kunde"
doc.save('TEST.docx')  

The output looks now like this: (everything is ok but i want to change the font-style)

enter image description here

So i tried this code:

from docx import Document
from docx.shared import Pt

file = "template.docx"
doc = Document(file)  

style = doc.styles['Normal']
font = style.font
font.name = 'Corbel'
font.size = Pt(10)

for idxPara, elemPara in enumerate(doc.paragraphs):
  if "«Kunde»" in elemPara.text:
    doc.paragraphs[idxPara].style = doc.styles['Normal']
    doc.paragraphs[idxPara].text = "Anderer Text für Kunde"

doc.save('TEST.docx')  

but unfortunately with this the style seems to work now - but the text in the paragraph is for whatevery reason on another position

enter image description here

How can i change the paragraph and also set the style of this paragraph?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source