Python 3 – String strip() Method
In Python, the strip() method is used to remove any leading or trailing whitespaces present in a string. It returns the new string after removing the whitespaces. The strip() method can be used with any string object in Python.
Syntax
The syntax of the strip() method is as follows:
string.strip([characters])
Parameters
The strip() method takes an optional parameter called characters, which specifies the characters to be removed from the string.
If no parameter is specified, the method removes whitespace characters from both ends of the string.
If the characters parameter is specified, the method removes all the characters present in it from both ends of the string.
Return Value
The method returns a string that is a copy of the original string with all the leading and trailing whitespaces removed.
Example 1: Basic Usage
# string with leading and trailing spaces
string_with_spaces = " Hello, World! "
# remove leading and trailing spaces
stripped_string = string_with_spaces.strip()
print(f"Original String: '{string_with_spaces}'")
print(f"Stripped String: '{stripped_string}'")
Output:
Original String: ' Hello, World! '
Stripped String: 'Hello, World!'
Example 2: Removing Specific Characters
# string with special characters
string_with_spaces = "-+-Hello, World!-+-"
# remove leading and trailing '-+-' characters
stripped_string = string_with_spaces.strip("-+")
print(f"Original String: '{string_with_spaces}'")
print(f"Stripped String: '{stripped_string}'")
Output:
Original String: '-+-Hello, World!-+-'
Stripped String: 'Hello, World!'
Conclusion
In this tutorial, we have learned about the Python 3 string strip() method. The method is used to remove any leading or trailing whitespace from a string. It takes an optional parameter that specifies the characters to be removed from the string.