Use strip() Function in Python with Example

The `strip()` function in Python is used to remove any leading (spaces at the beginning) and trailing (spaces at the end) characters (by default, it removes whitespace characters) from a string.

Syntax

string.strip([chars])

string: The original string on which the `strip()` function is applied.
chars(optional): A string specifying the set of characters to be removed. If not provided, it defaults to removing whitespace.

Example 1: Using `strip()` to Remove Whitespace

# Original string with leading and trailing whitespace
text = " Hello, World! "
# Use strip() to remove the whitespace
stripped_text = text.strip()
print(f"'{text}' after stripping is: '{stripped_text}'")

Output

' Hello, World! ' after stripping is: 'Hello, World!'

Example 2: Using `strip()` to Remove Specific Characters

# Original string with leading and trailing characters
text = "!!!Hello, World!!!"
# Use strip() to remove the specified characters
stripped_text = text.strip("!")
print(f"'{text}' after stripping '!' is: '{stripped_text}'")

Output

'!!!Hello, World!!!' after stripping '!' is: 'Hello, World'

Explanation

1. Removing Whitespace:

– In the first example, the `strip()` function is used to remove any leading and trailing spaces from the string. The original string had spaces at both the beginning and end, and after applying `strip()`, these spaces were removed.

2. Removing Specific Characters:

– In the second example, the `strip()` function is used to remove specific characters (‘!’) from the beginning and end of the string. Only the specified character (‘!’) is removed, while any other characters remain unchanged.