/  Technology   /  How to trim whitespace in Python?

How to trim whitespace in Python?

 

In this article, let’s learn how to trim the white spaces from a given string.

 

1.Using strip():

This string method removes the trailing and leading characters which may also have whitespaces from a string.

 

Example:

string_eg = "       Python by i2 tutorials       "

string_trim = string_eg.string()

print("Original String:", string_eg)
print("String after trimming:", string_trim)

Output:

 

The rstrip() method removes the trailing characters from a string and returns a copy of this trimmed string.

 

Example:

string_eg = "       Python by i2 tutorials       "

string_trim = string_eg.rstring()

print("Original String:", string_eg)
print("String after trimming:", string_trim)

Output:

 

The lstrip() method removes the leading characters from a string and returns a copy of this trimmed string.

 

Example:

string_eg = "       Python by i2 tutorials       "

string_trim = string_eg.lstring()

print("Original String:", string_eg)
print("String after trimming:", string_trim)

Output:

 

The leading or trailing newline (\n), return (\r) or tab (\t) characters are also considered as white spaces. If our original string contains these, they will be trimmed using all three methods, the strip(), lstrip() or rstrip() methods.

 

2. Using regular expressions:

A Regular Expression[RegEx] pattern is a five-letter string that starts with ‘a’ and ends with ‘s’.

^a...s$

We first have to import re module to work with these regular expressions[RegEx] 

 

Example:

import re

string_eg = "       Python by i2 tutorials       "

string_trim = re.sub(r'^\s+|\s+$', '', string_eg)

print("Original String:", string_eg)
print("String after trimming:", string_trim)

Output:

 

In the regex expression, ^ is known as caret which denotes if a string is starting with a specific character or not. \s denotes a whitespace and | denotes the or operation. $ is known as a dollar which denotes if a string is ending with a specific character or not.  +(Plus) symbol matches one or more occurrences of the pattern left to it.

 

Leave a comment