Python String strip()
Python String.strip() is used to strip/trim specified characters at the beginning and end of this string. strip() method returns a new resulting string and does not modify the original string.
In this tutorial, we will learn the syntax and examples for strip() method of String class.
Syntax
The syntax to call strip() method on string x
in Python is
x.strip(characters)
where
Parameter | Required / Optional | Description |
---|---|---|
characters | Optional | A string. Any of these characters that are present at the edges of the string shall be removed / trimmed. The default value is all whitespace characters. |
Examples
In the following program, we take a string '@.....hello world..@@@'
, and trim the characters '.@'
present at the edges of the string.
Example.py
x = '@.....hello world..@@@'
result = x.strip('.@')
print('Original String : ', x)
print('Stripped String : ', result)
Output
Original String : @.....hello world..@@@
Stripped String : hello world
Now, let us take a string with spaces on the left and right side, and trim this string using strip() method, with no arguments passed. Since the default value of characters
parameter is whitespaces, strip() trims the whitespace characters present around the string.
Example.py
x = ' hello world '
result = x.strip()
print('Original String : ', x)
print('Stripped String : ', result)
Output
Original String : hello world
Stripped String : hello world
Conclusion
In this Python Tutorial, we learned how to trim (specified) characters from the beginning and end of the string using strip() method, with examples.