How to remove whitespace from a text string in Python

Removing whitespace characters is a useful function to have, for example when dealing with user written input. So how are we going to get this into our project without wasting a bunch of time trying to set it up from a standing start? I’ll tell you, we can use an API to do it in a fraction of the time instead.

For our API, we will need to install its client first:

pip install cloudmersive-convert-api-client

Following that, instantiate the API, then use this instance to call edit_text_remove_all_whitespace:

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.EditTextApi(cloudmersive_convert_api_client.ApiClient(configuration))request = cloudmersive_convert_api_client.RemoveWhitespaceFromTextRequest() # RemoveWhitespaceFromTextRequest | Input requesttry:# Remove whitespace from text stringapi_response = api_instance.edit_text_remove_all_whitespace(request)pprint(api_response)except ApiException as e:print("Exception when calling EditTextApi->edit_text_remove_all_whitespace: %s\n" % e)

Now send the request and wait a few seconds for your de-whitespaced string. There is also a similar function that only removed leading and trailing whitespace, called edit_text_trim_whitespace.

Image for post

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