'How can I find and replace a text in footer of word document using "Python docx"

enter image description hereI have created a word document and added a footer in that document using python docx. But now I want to replace text in the footer.

For example: I have a paragraph in footer i.e "Page 1 to 10". I want to find word "to" and replace it with "of" so my result will be "Page 1 of 10".

My code:

from docx import Document
document = Document()
document.add_heading('Document Title', 0)
section = document.sections[0]
footer = section.footer
footer.add_paragraph("Page 1 to 10")
document.save('mydoc.docx')



Solution 1:[1]

I know this is an old question however the accepted answer changes the page number of the footer and requires editing of the XML if you want to fix that issue. Instead I have found that if you edit the text using Runs, it will keep the original format for your header/footer. https://python-docx.readthedocs.io/en/latest/api/text.html#docx.text.run.Run

from docx import Document
document = Document('mydoc.docx')
for section in document.sections:
    footer = section.footer
    footer.paragraphs[1].runs[0].text  = footer.paragraphs[1].runs[0].text.replace("to", "of")

document.save('mydoc.docx') 

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 sharder