Table of Contents
In this tutorial, we will learn about the Python String strip() method with the help of examples.
The strip() method returns a copy of the string by removing both the leading and the trailing characters (based on the string argument passed).
Example
message = ' Learn Python '
# remove leading and trailing whitespaces
print('Message:', message.strip())
# Output: Message: Learn Python
1. Syntax of String strip()
The syntax of the strip() method is:
string.strip([chars])
2. strip() Parameters
- chars (optional) – a string specifying the set of characters to be removed from the left and right part of the string.
The strip() method removes characters from both left and right based on the argument (a string specifying the set of characters to be removed).
Note: If the chars argument is not provided, all leading and trailing whitespaces are removed from the string.
3. strip() Return Value
strip() returns a copy of the string with both leading and trailing characters stripped.
4. Working of the strip() method
- When the character of the string in the left mismatches with all the characters in the
charsargument, it stops removing the leading characters. - Similarly, when the character of the string in the right mismatches with all the characters in the
charsargument, it stops removing the trailing characters.
5. Example: Working of the strip() method
string = ' xoxo love xoxo '
# Leading and trailing whitespaces are removed
print(string.strip())
# All <whitespace>,x,o,e characters in the left
# and right of string are removed
print(string.strip(' xoe'))
# Argument doesn't contain space
# No characters are removed.
print(string.strip('stx'))
string = 'android is awesome'
print(string.strip('an'))
Output
xoxo love xoxo lov xoxo love xoxo droid is awesome
Here, we can see that the first expression string.strip() without any arguments removed the whitespaces from the left and right of string.
string.strip(' xoe')– Removes all whitespace,x,o, andethat lead or trailed the string.string.strip('stx')– Sincestringhas whitespace at the beginning and end, this expression does not change the string.xis not removed since it is at the middle of the string (whitespaces lead and trail the string)string.strip('an')– Removesanleading the string.