Whitespace characters can be spaces, tabs, newlines, carriage returns. Basically whitespace is something that represents the spaces between words and lines. In this article, we will discuss different ways to remove all whitespace characters from a string in python. These different ways are,

  • Using for loop and string.whitespace
  • Using split() and join()
  • Using translate() and translation table.
  • Using Regex

Let’s explore these techniques one by one,

Remove whitespace from a string in Python using string.whitespace

In python, string.whitespace is a string constant that contains all the whitespace characters i.e. ‘ \t\n\r\v\f’. Its contents are space, tab, linefeed, return, form feed, and vertical tab. We can iterate all the whitespace characters in string.whitespace and for each type of whitespace character, we can delete all its occurrences from the given string. For example,

import string

sample_str = "  This  is  \t a \r\n Sample \n String   "

# Remove all whitespace characters from a string
for elem in string.whitespace:
    sample_str = sample_str.replace(elem, '')

print(sample_str)

Output:

ThisisaSampleString

It deleted all the whitespace characters from the given string.

Remove whitespace from a string in Python using split() and join()

In Python, the string provides a function str.split(sep). It return a list of the words in the given string, using sep as the delimiter string. The default value of sep is whitespace character. So, if we call the split() function on given string object without any sep argument, then it splits the string using whitespace characters and returns a list of words. There will be no whitespace characters in the list of string returned by split() function. Then we can join all the strings in list using join() function and get a final string that contains no whitespace characters. For example,

sample_str = "  This  is  \t a Sample \n String   "

# Remove all whitespace characters from a string
sample_str = ''.join(sample_str.split())

print(f"'{sample_str}'")

Output:

'ThisisaSampleString'

It removed all the whitespace characters from the given string.

Remove whitespace from a string using translate()

In Python, the string provides a function translate(). It accepts a translation table as an argument and replaces the characters in string based on that translation table. We can create a translation table where each type of whitespace character is mapped to empty string i.e. ”. Translation table will be like this,

  • ‘ ‘ —> ”
  • ‘\t’ –> ”
  • ‘\n’ –> ”
  • ‘\r’ –> ”
  • ‘\v’ –> ”
  • ‘\f’ –> ”

For the above mapping we can use a dictionary as the translation table. Then pass this translation table to translate() function as argument. Due to which translate() function will replace all whitespace characters in the calling string object by empty string. For example,

import string

sample_str = "  This  is  \t a Sample \n String   "

# Create a dict where each type of whitespace 
# character is mapped to empty string
translation_table = {   ord(cr): None 
                        for cr in string.whitespace }

# Remove all whitespace characters from a string
sample_str = sample_str.translate(translation_table)

print(f"'{sample_str}'")

Output:

'ThisisaSampleString'

It removed all the whitespace characters from the given string.

Remove whitespace from a string using regex

In Python, the regex module provides a function to replace the contents of a string based on a matching regex pattern,

sub(pattern, replacement_str, original_str)

We can use this to remove whitespace characters from a string. For this we need to pass a regex pattern that matches all the whitespace characters like ‘\s+’. Also, as a replacement string we need to pass a empty string. For example,

import re

org_string = "  This  is  \t a Sample \n String \t   "

# Remove all whitespace characters from a string
sample_str = re.sub(r"\s+", "", org_string)

print(f"'{sample_str}'")

Output:

'ThisisaSampleString'

It removed all the whitespace characters from the given string.

Summary:

We learned about different ways to remove all whitespace characters from a string in python.