How to Replace a Text String in a Word (DOCX) Document in Python

Cloudmersive
2 min readJan 27, 2021

Do you need to find and replace a text string in a Word document? If so, we have an API that will transform the operation into a simple and efficient process. This article will provide step-by-step instructions on how to use this helpful Cloudmersive API in Python.

Without further ado, let’s get started! First, we need to install the package:

pip install cloudmersive-convert-api-client

Then, we are going to call the function with the following code:

from __future__ import print_function
import time
import cloudmersive_convert_api_client
from cloudmersive_convert_api_client.rest import ApiException
from pprint import pprint
# Configure API key authorization: Apikey
configuration = cloudmersive_convert_api_client.Configuration()
configuration.api_key['Apikey'] = 'YOUR_API_KEY'
# create an instance of the API class
api_instance = cloudmersive_convert_api_client.EditDocumentApi(cloudmersive_convert_api_client.ApiClient(configuration))
req_config = cloudmersive_convert_api_client.ReplaceStringRequest() # ReplaceStringRequest | Document string replacement configuration input
try:
# Replace string in Word DOCX document
api_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)

All you have to do is insert your API key and the text string you want to search/replace, and your document will be modified according to your request! To retrieve your free API key, head to the Cloudmersive website to register for an account and gain access to 800 monthly calls across our many APIs.

--

--

Cloudmersive

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