The Python String strip() Method

The string strip() method in Python removes the leading and trailing characters from a string and returns a new string. The characters that are to stripped are based on a string of characters passed into the strip() method.

 

In this tutorial, we will learn how to use the strip() method in Python using examples to understand its behaviour.

 

The strip() Syntax

The strip() method is passed after a string using a . (dot). Inside the () (parenthesis) of the method, an optional set of characters to look for at the beginning and end of the string can be included – if nothing is passed Python will remove all white spaces from the start and end of the string.

 

string.strip([chars])

 

Remove All Leading and Trailing Whitespaces in a String

strip() is useful if you need to remove all the space characters at the beginning and of a string. To do this don't pass anything inside the parenthesis of strip().

 

string = '   hello  '

stripped = string.strip()

print(stripped)
hello

 

You could achieve the same as above with a small bit of regex, but with strip() it is cleaner.

 

Removing Specific Characters from Start and End of a String

To remove specific characters from the end of a string pass them inside the parenthesis of strip(). So long as at least one of the supplied characters is next in from the end as strip() moves sequentially inward it will be removed. Let's try this out with the string hannah to remove the characters h and a from each end of the string.

 

string = 'hannah'

stripped = string.strip('ahw')

print(stripped)
nn

 

Let's see how the same code as above works except this time with a character after the first h which is not included in the strip() method.

 

string = 'h!annah'

stripped = string.strip('ahw')

print(stripped)
!ann

 

Conclusion

You now know how to use the strip() method and how it behaves when removing characters from a string.

string remove method

Related Tutorials

 thumbnail

Python Print Formatting

September 24, 2020