Remove Whitespace From String in Python Using Regular Expression

(Last Updated On: 24/03/2023)

Python Program to Remove Whitespace From String Using Regular Expression

# Remove Whitespace From String in Python Using Regular Expression
import re

my_string  = " Hello World "

# \s denotes the whitespace and \ is the or operator. + one or more occurrences of the pattern left to it.

output = re.sub(r'^\s+\+$', '', my_string)
print(output)

Output:

Hello World

Leave a Reply

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