Remove whitespace from the start and end of a string in Python

In Python, there are several methods for eliminating spaces from a string. The goal of this lesson is to give a brief illustration of each technique we might use to eliminate whitespace from a string.

Python function to eliminate white space from a string

We cannot alter the value of a Python String since it is immutable. Any function that alters a string value produces a brand-new string, which must be explicitly assigned to the original string. The string value won’t change in any other case.

Let’s examine several functions for removing white spaces.

1. strip() to eliminate leading and ending whitespaces from a string in Python

Leading and ending whitespaces will be eliminated using the Python String strip() method.

Python Code will be:

a=" Amandeep Singh "
print(a.strip())

Output:

Amandeep Singh

2. replace() to eliminate all whitespaces

To eliminate all whitespace from the string, use replace(). The whitespace in between words will also be eliminated by this function.

Python Code will be:

a=" Amandeep Singh "
print(a.replace(" ", ""))

Output:

AmandeepSingh

You can check: Remove all the whitespaces from the end of a string in Python

3. join() with split() to remove duplicate whitespaces and \n

Use the join() method along with the string split() function to eliminate any duplicate whitespace and newline characters.

Python Code will be:

a=" Amandeep Singh \n Codespeedy"
print(a)
print("Use join() with split()")
print( " ".join(a.split()))

The output will be:

Amandeep Singh 
Codespeedy
Use join() with split()
Amandeep Singh Codespeedy

4. Using Regex to remove whitespaces

Additionally, we may match whitespace with a regular expression and eliminate it using the re.sub() method.

Python Code will be:

import re
a=" Amandeep Singh Codespeedy"
print(re.sub(r"^\s+|\s+$", "", a), sep='')  # | for OR condition

The output will be:

Amandeep Singh Codespeedy

So these are some ways through which you can remove whitespace from the start and end of a string in Python. I hope you like this article.

Leave a Reply

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