The String strip() method removes any whitespaces from the beginning (leading) and end (trailing) of the string by default.
Syntax
my_string.strip(chars)strip() Parameters
Python String strip() method parameters:
| Parameter | Condition | Description |
|---|---|---|
chars |
optional | A string of characters to be removed from the string |
strip() Return Value
Python String strip() method returns a copy of the string with leading and ending characters stripped.
All combinations of characters in the chars parameter are removed from both the beginning and the end of the string until the first mismatch.
Examples
Example 1: Strip Whitespaces with strip()
The strip() method allows to remove spaces from both the left side and the right side of a string, returning a new string.
my_str = " Hello "
result = my_str.strip()
print(f"'{result}'") # Output: 'Hello'output
'Hello'Note that newline \n, tab \t and carriage return \r are also considered whitespace characters!
my_str = " \t\n\r Hello \t\n "
result = my_str.strip()
print(f"'{result}'") # Output: 'Hello'output
'Hello'Example 2: Strip Characters with strip()
By specifying the chars parameter, you can also specify the character you want to strip.
my_str = "aaabbbaaa"
result = my_str.strip('a')
print(result) # Output: bbb output
bbbExample 3: Strip Multiple Characters with strip()
The chars parameter is not a prefix! All combinations of its values are stripped, until reaching a character of the string that is not contained in the set of characters in chars parameter.
For example, let's strip all the characters provided in the argument:
my_str = 'www.example.com'
result = my_str.strip('cmowz.')
print(result) # Output: example output
example