In python, the string strip() method is useful to remove leading (Beginning) and trailing (End) whitespace characters from the specified string and return the trimmed version of the string.
Using a string strip() method, you can also remove all the specified characters' occurrences from the start and end of the specified string.
Following is the pictorial representation of string strip() method functionality in python.
If you observe the above diagram, we are trying to remove the leading and trailing whitespaces from the specified string " Welcome to Tutlane "
using python's strip
function. The strip()
method has returned the string by removing the string's trailing and leading spaces.
Following is the syntax of defining a string strip method in python to remove leading/ trailing whitespaces or specified characters from the string.
The first strip()
method syntax is useful for removing the leading and trailing whitespaces from the specified string and won’t take any parameters.
The second strip()
method syntax is useful to remove the leading and trailing occurrences of the specified characters from the specified string.
Following is the example of removing the spaces and specified characters from the string using the strip()
function in python.
If you observe the above example, we used the strip()
function with/without characters to remove leading/trailing whitespaces and specified characters from the string.
When you execute the above python program, you will get the result as shown below.
The strip()
function is removing the spaces and specified characters from both leading and trailing ends from the given string. If you want to remove only the leading or trailing spaces/characters, you need to use either lstrip()
or rstrip()
functions based on your requirements.
In python, the lstrip()
method is useful for removing all the leading or starting occurrences of the spaces/characters from the given string and returning the string's left trim version.
Following is the example of removing the leading spaces and specified characters from the given string in python.
The above lstrip()
method example will return the result as shown below.
Same as the lstrip()
method, the rstrip()
method is useful to remove only the trailing or ending occurrences of the spaces/characters from the given string and return the string's right trim version.
Following is the example of removing the trailing spaces and specified characters from the given string in python.
The above rstrip()
method example will return the result as shown below.
This is how you can use the string strip()
, lstrip()
, and rstrip()
methods in Python to trim/remove leading and trailing spaces or specified characters from the given string based on your requirements.