How to search and replace a Text String in a Word DOCX in Python

Search and replace is such a common action that we tend to take it for granted. This will quickly change if you have ever tried setting it up from the ground up, as it can rapidly devolve into messy code and heartache. Today’s solution will skip right over that whole pitfall.

We will be using the Cloudmersive Document/Convert API for this, so installing the client is our first step:

pip install cloudmersive-convert-api-client

Using the API itself is pretty straightforward. We start by authorizing our free key, then instancing the API class. Finally, call edit_document_docx_replace from that instance.

from __future__ import print_functionimport timeimport cloudmersive_convert_api_clientfrom import ApiExceptionfrom pprint import pprint# Configure API key authorization: Apikeyconfiguration = cloudmersive_convert_api_client.Configuration()configuration.api_key['Apikey'] = 'YOUR_API_KEY'# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed# configuration.api_key_prefix['Apikey'] = 'Bearer'# create an instance of the API classapi_instance = cloudmersive_convert_api_client.EditDocumentApi(cloudmersive_convert_api_client.ApiClient(configuration))req_config = cloudmersive_convert_api_client.ReplaceStringRequest() # ReplaceStringRequest | Document string replacement configuration inputtry:# Replace string in Word DOCX documentapi_response = api_instance.edit_document_docx_replace(req_config)pprint(api_response)except ApiException as e:print("Exception when calling EditDocumentApi->edit_document_docx_replace: %s\n" % e)

And we are officially walking on easy street. That’s right, all done! If you look through the rest of this library, you will see functions for everything from merging documents to converting between formats.

Image for post
Image for post

Written by

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store