Last Updated On By Anmol Lohana
In Python programming, many inbuilt functions exist, and the strip function is one of them. We use the Python string strip() method to remove the white spaces and unwanted characters from the given string.
This function removes whitespaces in string or characters from the beginning and end of the string. The strip() method accepts only one argument as a parameter, the character or a string. The character/string parameter is an optional argument.
Table of Contents
string.strip([character])
After passing a character argument or a string argument as an optional parameter to the strip method, it will remove it from the string’s start and end. The parameter is optional, so if we don’t pass it, then the strip() method will remove the whitespaces from beginning and end by default.
It will return the original string’s copy by removing the leading whitespaces and trailing position if the character/string is not specified. If the string doesn’t contain any whitespaces, the strip() method will return the resultant string as it is.
If the character/string is specified and there is a match for that in the string, the strip() method will remove the specified character/string and return the string’s rest. If the specified parameter does not match with the original string, strip() will return the string as it is.
Let’s have a look at examples in different criteria.
string = "Wellcome to Code Leaks"
striped_string = string.strip()
print(striped_string)
string = " Wellcome to Code Leaks "
striped_string = string.strip()
print(striped_string)
string = " ***Wellcome to Code Leaks***"
striped_string = string.strip(“*”)
print(striped_string)
string = " ***Wellcome to Code Leaks***"
striped_string = string.strip(“!”)
print(striped_string)
We can apply the strip() method only on string and character datatype; it will throw an error if we try it on another datatype. Let’s have a look.
List = ["Code", "Leaks"]
striped_list = List.strip()
print(striped_list)
In this article, we discussed the strip in Python built-in function and how we can remove unwanted whitespaces, characters, and strings from a given string. The strip() method contains two more methods lstrip() method and rstrip() method.
If we want to remove whitespaces, characters, and string only from the left side, we can use the lstrip method, and if we want to remove whitespaces, characters, and string only from the right side, we can use the rstrip method.