Remove all the whitespaces from the end of a string in Python

In this tutorial, we will learn how to remove whitespaces from the end of a string in Python with the help of various examples including basic and both advanced.

Firstly, we should know that the strings are immutable. So, we can not modify the previously declared string only thing we can do is explicitly assign the modified string in the string.

We can remove whitespaces at the end, from the starting or all whitespaces or unwanted ones, etc, but these require different methods and functions. So, to remove whitespaces from the end of string there are various ways. These are explained below.

Remove Whitespaces from the end In Python

Initial code:

text="  Hey Learner... How are you all ??   "
print(text)
OUTPUT :-
  Hey Learner... How are you all ??

The various ways to remove the whitespaces are:-

 Trim trailing space –

Remove space at the end of the string in Python.

text.rstrip()

OUTPUT:

'  Hey Learner... How are you all ??'

Trim spaces using Regex module –

Remove spaces using regular expressions.
For using this we need to import a built-in package re which is generally used for regular expressions.
Before using its function we need to know some important characters with its meaning.

^   String Starts with                              (^hello)
$   String Ends with                                (hello$)
+   One or more than one occurance   (hello+)
|    Or statement                                       (^hello|hello$)

import re
text="  Hey Learner... How are you all ??   "
print(text)

OUTPUT:

  Hey Learner... How are you all ??

The method which we will use is re.sub().

print("Remove all the spaces at the ending of a string:- ",re.sub("\s+$","",text))

OUTPUT:

Remove all the spaces at the ending of a string:-    Hey Learner... How are you all ??

You may also learn:-

File truncate method in Python

Leave a Reply

Your email address will not be published.