Python Program to Trim Whitespace From a String – 2024

Python Tutorials MLP Feature Image

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

Leave a Comment

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

Scroll to Top