Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Find and Replace Text in Word Documents using Python

Learn how to find and replace text in Word documents using Python:

import aspose.words as aw
# load Word document
doc = aw.Document("document.docx")
# create options
findReplaceOptions = aw.replacing.FindReplaceOptions()
findReplaceOptions.apply_paragraph_format.alignment = aw.ParagraphAlignment.CENTER
# double each paragraph break after word "section", add kind of underline and make it centered.
count = doc.range.replace("section&p", "section&p----------------------&p", findReplaceOptions)
# insert section break instead of custom text tag.
count = doc.range.replace("insert-section", "&b", findReplaceOptions)
# save the modified document
doc.save("updated.docx")
import aspose.words as aw
# load Word document
doc = aw.Document("document.docx")
# replace text using RegEx
options = aw.replacing.FindReplaceOptions()
doc.range.replace_regex("[s|m]ad", "bad", options)
# save the modified document
doc.save("updated.docx")
import aspose.words as aw
# load Word document
doc = aw.Document("document.docx")
# replace text
doc.range.replace("sad", "[replaced]", aw.replacing.FindReplaceOptions(aw.replacing.FindReplaceDirection.FORWARD))
# save the modified document
doc.save("updated.docx")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment