In this artile, we will disciss two different ways to remove leading whitespace from a string i.e. removing whitespace from start of string. These two ways are,
- Using lstrip() function
- Using regex module’s rsub() function
Let’s see both the techniques one by one,
Remove whitespace from the start of string using lstrip()
In Python, string provides a function lstrip(). It returns a copy of the calling string object after removing all the whitespace characters from the start of string. Basically it strips the whitespace characters from the left of string i.e. the start of string. For example,
sample_str = " \t\n This is an another Sample Text \t " # Removing leading whitespaces from a string sample_str = sample_str.lstrip() print(f"'{sample_str}'")
Output:
'This is an another Sample Text '
It removed the leading whitespace from the given string.
Frequently Asked:
Remove whitespace from the start of string using regex
In Python, the regex module provides a function sub(). It replaces the contents of a string based on a given matching regex pattern. Its signature is like this,
sub(pattern, replacement_str, original_str)
We can use this to remove leading whitespace from a string. For this we need to pass a regex pattern that matches one or more whitespace characters, in the starting of string like r”^\s+”. Also, as a replacement string we need to pass the empty string. For example,
import re sample_str = " \t\n This is an another Sample Text \t " # Removing leading whitespaces from a string sample_str = re.sub(r"^\s+", "", sample_str) print(f"'{sample_str}'")
Output:
'This is an another Sample Text '
It removed the leading whitespace from the given string.
Latest Python - Video Tutorial
Summary:
We learned about two ways to remove leading whitespace from a string in python.
Latest Video Tutorials