Python string strip() method

Python strip() method returns the cop of the string removing leading and trailing white spaces from the string. This method by default removes white spaces but if you want to remove another character then you can also do so.

Basic Syntax

string.strip([chars])

And the parameters are:

Parameter Description
chars (Optional) This is an optional parameter if you provide a character then it will remove that char at start and end of the string. The default value is white space.

Return Value

strip() method returns the copy of the string removing spaces from front and end of the string.

Example

Following are some examples illustrating the Python strip() function.

Example 1

# Python program for the working of strip() method

string = '  Hello Crazy Geeks               '
  
# removes white spaces
print(string.strip()) 
  
# do not match
print(string.strip('Hi'))
  
# removes Hello
print(string.strip('  Hello')) 

The output should be:

Hello Crazy Geeks
Crazy Geeks
Hello Crazy Geeks

Example 2

# Python code for Pyhon strip() function 
string = '###Hello Crazy Geeks###'

# remove all #
print(string.strip('#')) 

string = 'HelloCrazyGeeks'

# removes Geeks 
print(string.strip('skeeG')) 

The output should be:

Hello Crazy Geeks
HelloCrazy