Python Program to Trim Whitespace From a String – 2024

Hey guys, in this blog we will see a Python Program to Trim Whitespace From a String.

Table of Contents

Example 1: Using strip()

my_string = " Machine Learning Projects "

print(my_string.strip())

Output

Machine Learning Projects

However, if you have characters in the string like '\n' and you want to remove only the whitespaces, you need to specify it explicitly on the strip() method as shown in the following code.

my_string = " \nMachine Learning Projects "

print(my_string.strip(" "))

Output


Machine Learning Projects

Here only the space character is stripped. The new line character ‘\n’ is still there.

Example 2: Using regular expression

import re

my_string = " Machine Learning Projects "
output = re.sub(r'^\s+|\s+$', '', my_string)

print(output)

Output

Machine Learning Projects

Here we have used regex to remove special characters including space characters from our string.

Check out our other python programming examples

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 520

Subscribe to our Newsletter

Subscribe to our newsletter and receive all latest projects...

Leave a Reply

Your email address will not be published. Required fields are marked *