Python String Strip – With Examples

In python, the string function strip() gives a copy of the string with leading and trailing spaces removed. In this tutorial we’ll be looking its syntax and use-cases along with some examples.

Before we proceed, here’s a quick refresher on python strings – Strings are immutable sequences of unicode characters used to handle textual data. Strings implement all common sequence operations (example, iterations, membership tests, etc). For more, check out our guide on strings and other fundamentals of python.

As stated already, strip() is a python string function used to remove leading and trailing spaces but it can be used to remove any given characters from the starting and end of the string. It is quite frequently used for text formatting purposes, for example, cleaning texts in forms filled out by users. The following is the syntax:

sample_string.strip(chars)

Here, sample_string is the string you want to truncate the leading and trailing chars from.

Parameters:

  • chars (optional): String specifying the set of characters to be removed. If it’s not provided, it defaults to removing all the leading and trailing whitespace characters.

Returns: It returns a copy of the string with the leading and trailing chars removed.

Note: Strings are immutable and hence cannot be changed, string functions like strip() return a copy of the string with its operations performed.

Example 1: Using the strip() function without any arguments

# strip() function to remove whitespace characters
s1 = "Python strings are immutable"
s2 = "  Python strings are immutable     "
s3 = " \t\tPython strings are immutable \t\t"

# using the strip() function on the above strings
print(s1.strip())
print(s2.strip())
print(s3.strip())

Output:

Python strings are immutable
Python strings are immutable
Python strings are immutable

In the above example, the return values from applying the strip() function on strings s1, s2, and s3 are the same because, by default, the strip() function removes all the leading and trailing whitespace characters. Note that the tab space character '\t' is also one of the whitespace characters in python.

Example 2: Using the strip() function to remove custom characters

# strip() function to remove custom characters
s = "c co cod code gives bugs on running the code cod co c"

# using the strip() function
print(s.strip(' code'))

Output:

gives bugs on running th

In the above example, we pass the string ' code' as an argument to the strip() function. This results in the function removing all instances of characters ' ', 'c', 'o', 'd', 'e' from the starting and end of the string s.

For more on string functions refer to the python docs.


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.