The Python String strip() Function
In this article, we’ll examine how to strip characters from both ends of a string in Python.
The built-in String
type is an essential Python structure, and comes with a built-in set of methods to simplify working with text data. There are many situations in which a programmer may want to remove unwanted characters, i.e. strip certain characters, from either the beginning or ending of a string.
The most common requirement is to strip whitespace (spaces, tabs, newline characters, etc.) from both ends of a string. This usually occurs after importing raw text data from a file, database, web service, or after accepting user input, which may contain typos in the form of extra spaces. This can be handled by the default usage of the String.strip()
method, as seen here:
>>> orig_text = ' The cow jumped over the moon! n'
>>> print(orig_text.strip())
The cow jumped over the moon!
>>>
Note that this method does not change the original value of the string, i.e. it does not change the string in-place. It simply returns a new string with the whitespace on either end stripped out. We can verify this by printing out the original string:
>>>