How to Replace String in Microsoft Word (DOCX) and Return Result using Python
Making programmatic changes to common document types can help save you (or your team) a ton of time. Using complementary Python code examples provided below, you can easily take advantage of an API solution which allows you to replace all instances of a text string within a Microsoft Word DOCX document. This API accepts a file path or file URL to begin making your edits and will replace the value entered in the “matchString” input with the value entered in the “replaceString” input.
To implement this API, begin by running the following command to install the Python SDK:
pip install cloudmersive-convert-api-client
Once that’s done, copy in the remaining code examples, beginning with the imports:
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.TransformDocumentApi(cloudmersive_convert_api_client.ApiClient(configuration))
match_string = 'match_string_example' # str | String to search for and match against, to be replaced
replace_string = 'replace_string_example' # str | String to replace the matched values with
input_file = '/path/to/inputfile' # file | Optional: Input file to perform the operation on. (optional)
input_file_url = 'input_file_url_example' # str | Optional: URL of a file to operate on as input. This can be a public URL, or you can also use the begin-editing API (part of EditDocumentApi) to upload a document and pass in the secure URL result from that operation as the URL here (this URL is not public). (optional)
match_case = true # bool | Optional: True if the case should be matched, false for case insensitive match. Default is false. (optional)
try:
# Replace string in Word DOCX document, return result
api_response = api_instance.transform_document_docx_replace(match_string, replace_string, input_file=input_file, input_file_url=input_file_url, match_case=match_case)
pprint(api_response)
except ApiException as e:
print("Exception when calling TransformDocumentApi->transform_document_docx_replace: %s\n" % e)
To complete your API call, include a free-tier Cloudmersive API key in the configuration line above. You can get one by registering a free account on our website, which will provide a limit of 800 API calls per month with no commitments.
It’s just that easy — you’re all done!