Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python String strip()
In this tutorial, we will learn about the Python String strip() method with the help of examples.
The strip() method removes any leading (starting) and trailing (ending) whitespaces from a given string.
Example
message = ' Learn Python '
# remove leading and trailing whitespaces
print(message.strip())
# Output: Learn Python
String strip() Syntax
string.strip([chars])
strip() Arguments
The method takes an optional parameter - chars:
- chars - specifies the set of characters to be removed from both the left and right parts of a string
Note: If the chars argument is not provided, all leading and trailing whitespaces are removed from the string.
strip() Return Value
The method returns a string after removing both leading and trailing spaces/characters.
Example 1: Remove Whitespaces From String
string = ' xoxo love xoxo '
# leading and trailing whitespaces are removed
print(string.strip())
Output
xoxo love xoxo
Example 2: Remove Characters From String
string = ' xoxo love xoxo '
# all <whitespace>,x,o,e characters in the left
# and right of string are removed
print(string.strip(' xoe'))
Output
lov
Notes:
- Removes characters from the left until a mismatch occurs with the characters in the
charsargument. - Removes characters from the right until a mismatch occurs with the characters in the
charsargument.
Example 3: Remove Newline With strip()
We can also remove newlines from a string using the strip() method. For example,
string = '\nLearn Python\n'
print('Original String: ', string)
new_string = string.strip()
print('Updated String:', new_string)
Output
Original String: Learn Python Updated String: Learn Python
Also Read:
Did you find this article helpful?