In this tutorial, we’ll learn what Python string strip() method is and how to properly use it. We’ll go through multiple Python code examples to understand how strip() method works.
Introduction: Python String strip() Method
This method returns a string after removing the leading and trailing characters from it and its based on the string passed as an argument to this method.
Syntax of strip() Method
string.strip(str(optional))
- Python string strip method takes a string argument.
- This argument is optional and it specifies the characters to be removed from the left and right side of string.
- If no argument is passed to strip method then only the whitespaces from left and right are removed from string.
- Python string strip method return a new string with leading and trailing characters stripped(only whitespaces will be removed if no argument is passed).
Example 1: strip() Method with no Parameter
print('Python'.strip()) print('Python '.strip()) print(' Python'.strip()) print(' Python '.strip())
Output
Python Python Python Python
Python string strip() method remove whitespaces from left and right as no string argument is passed to it.
Example 2: strip() Method with String Parameter
print('xox'.strip('x')) // x removed from leading and trailing print('xxox'.strip('x')) // each and every x is removed from leading and trailing print('xoxox'.strip('x')) // x removed until a non x character is found print(' xox'.strip('x')) // x removed from trailing, leading has whitespace before x print(' xox'.strip(' x')) // x and whitespace removed as specified in argument passed to strip method print(' xox '.strip('y')) // nothing removed as y doesnot come in leading or trailing print(' xoxy '.strip(' xy')) // xy removed from trailing and whitespace removed from leading print(' xox g- '.strip(' g-')) // g- removed from trailing and whitespace removed from leading
Output
o o oxo xo o xox o xox
You can try it with other examples to better understand how Python string strip method works with argument.
Example 3: strip() Method Return Value
val=' fffrggxoxhdhrrf ' returnedVal=val.strip('rffr ') print(returnedVal)
Output
ggxoxhdh
Python string strip method return a new string with all the matching specified characters(passed as a string argument to strip method) stripped from leading and trailing.
Conclusion
To conclude this tutorial, hope you now have a detailed practical understanding of how to properly use Python string strip method. I’d be very delighted to have your feedback on this post. Thank you for reading it.