Strip String Whitespace in Python

In this tutorial, we will introduce the method to remove whitespaces in a python string.

1. Create a text string in python

text_data = [' This is a test  ',
             ' cocyer.com ,  it is a good site. ',
             '   i love this site   ']

2. Strip whitespaces in string

We can use python string.strip() function to strip whitespaces.

strip_whitespace = [string.strip() for string in text_data]
print(strip_whitespace)

The strip_whitespace  will be:

['This is a test', 'cocyer.com ,  it is a good site.', 'i love this site']

3. Strip whitespaces which are not at the beginning or end of python string

We will create a python function stripBlank() to implement it.

import re
def stripBlank(text):
    pattern = re.compile(r'[ ]{2,}')
    text = re.sub(pattern, ' ', text)
    
    return text.strip()

Then we can use this function to remove whitespaces in a python string.

strip_whitespace = [stripBlank(string) for string in text_data]
print(strip_whitespace)

The strip_whitespace will be:

['This is a test', 'cocyer.com , it is a good site.', 'i love this site']