Register Login

Python String strip()

Updated Apr 03, 2020

While programming in Python, you might have to remove certain characters and spaces from strings. For this, you can either manually remove the required characters and spaces. But in case the strings s complicated or there is a huge chunk of text to handle, manual removal of characters will be difficult.

For your convenience, Python offers a method called strip(). We will understand the different features of this method in this article and the various ways to use it.

Python strip() Function can be used for:

  1. Strip Whitespace from the Beginning and End of a String
  2. Remove Specific Characters from the Beginning and End of a String String
  3. Strip Multiple Characters from the Beginning and End of a String
  4. Stripping of a Number from the Beginning and Start of the String
  5. Strip Newline Character from the Beginning and Start of the String
  6. Show strip() Tab from String
  7. Removing Quotes from Beginning and End of a String

Let us understand the basics of this method first.

What is Python String strip()

The strip() method in Python is used for removing all the spaces in the beginning and end of a string. This removes the spaces from the left and the right of a string.

Syntax

string.strip([chars])

In the syntax above, chars are the optional parameter that is used for specifying the set of characters needed to be removed from the string. This is an optional argument, and if this is not mentioned, all the whitespace characters from the beginning of the string and the end are removed.

Parameter

The method can take one or no parameter.

Return Value

The method returns a string with all the leading and trailing characters removed. But there are two conditions:

  • If the characters in the charsargument do not match with the characters of the string on its left, strip()  stops removing leading characters
  • If the characters in the charsargument do not match with the characters of the string on its right, strip()  stops removing trailing characters

Strip Whitespace at the Beginning and End of a String

Example          

# Python program to show use of strip() method
string = '       Stechies      '
# Prints the string without using strip() method
print('String before strip: ',string)
# Prints the string after using strip() method
print('String after using strip: ',string.strip())

Output

String before strip:         Stechies
String after using strip:  Stechies

In the code written above, you can see that the strip() method has been used for removing whitespaces from the string '       Stechies      '. As there are no parameters mentioned within the method, all leading and trailing whitespaces are removed from the string.  

Remove Specific Characters from Beginning and End of a String

You can remove specific characters from string by passing parameters along with the strip() method.  

Example

# Python program to show use of strip() method
string = '########Stechies#######'
# Prints the string without using strip() method
print('String before strip: ',string)
# Prints the string after using strip() method
print('String after using strip: ',string.strip('#'))

Output

String before strip:  ########Stechies#######
String after using strip:  Stechies

In this program, the strip() method is used for removing the ‘#’ character from the string. As it is passed as the argument and it perfectly matches with the string, it is deleted from the beginning and the end.  

Strip Multiple Characters From the Beginning and End of a String

Example 

# Python program to show the use of strip() method
string = '@#@ Welcome@#@Stechies@#@'
# Prints the string without using strip() method
print('String before strip: ',string)
# Prints the string after using strip() method
print('String after using strip: ',string.strip('@#@'))

Output

String before strip:  @#@ Welcome@#@Stechies@#@
String after using strip:   Welcome@#@Stechies

In the code provided above, the strip() method is used for removing the '@#@' character from the string. As it is passed as an argument, the method checks whether it matches the initial and trailing characters of the string. As it perfectly matches with the string, it is deleted from the beginning and the end, resulting in the final string Welcome@#@Stechies.  

Stripping of a Number from the Beginning and Start of a String

Example

# Python program to show use of strip() method
string = '123123533=stechies,231'
# Prints the string without using strip() method
print('String before strip: ',string)
# Prints the string after using strip() method
newstr = string.strip("123456789=,")
print('String after using strip: ',newstr)

Output

String before strip:  123123533=stechies,231
String after using strip:  stechies

In this program, the strip() method is used for removing the specified numbers from the beginning and end of the string that is stored in variable newstr.

Strip Newline Character from Beginning and End of a String

Example

# Python program to show use of strip() method
# Strip newline character from string
string = '\n\nstechies\n'
# Prints the string without using strip() method
print('String before strip: ',string)
# Prints the string after using strip() method
newstr = string.strip("\n")
print('String after using strip: ',newstr)

Output

String before strip:
stechies
String after using strip:  stechies

Here, the strip() method is used for removing the newline character from the string. The newline character is represented by \n that takes the cursor to the newline. As two newline characters are mentioned before the string stechies, the string is printed after a gap of two lines.

But with the strip() method, this newline character is passed as the argument. The method checks all the newline characters in the string and removes them – two \n at the beginning and one \n at the end. The resultant string without these characters is stechies.

Another example of stripping the newline characters from a string is given below:

Example

str1='Python Exercises\n'
print(str1)
print(str1.rstrip())

Output

Python Exercises
Python Exercises

Here, the newline character is removed using a variant of the strip method called the rstrip() method. This method removes all the trailing characters of a string, based on its arguments. If no arguments are passed, all trailing spaces are removed from the string. So, when this method is provided with the \n argument, it removes the newline characters in the right of the string.      

Show strip() Tab from String

# Python program to show the use of strip() method
# Strip newline character from string
string = '\t\tstechies\t'
# Prints the string without using strip() method
print('String before strip: ',string)
# Prints the string after using strip() method
newstr = string.strip("\t")
print('String after using strip: ',newstr)

Output

String before strip:            stechies
String after using strip:  stechies

The code here depicts how to remove tab characters from strings. The tab character is represented by a \t, which puts a space or tab before or after the string along with which it is specified. Before using the strip() method, there were two tabs before the string, and one after it, as specified by “\t\t”. As the \t is passed as an argument to the method, all tabs are removed from the beginning and the end.

The rstrip() method can be used to remove whitespace from the string too.

How to Strip a List in Python?

You can use the strip() method to remove specific characters from a list of strings. Let us look at an example:

Example

n = ['01', '1.0', '[0.2]']
n = [i.strip('[]') for i in n]
print(n)

Output

['01', '1.0', '0.2']                        

In this code, the n variable holds a list of certain string elements. Then the strip() method is used along with a for loop to remove the character ‘[]’ from the string. So, this loop iterates over the elements of the list n and removes all instances of ‘[]’ from the string. The result is the list is ['01', '1.0', '0.2'].

Removing Quotes from Beginning and End of a String

The strip() method is used for removing quotes from strings. Let us look at an example:

Example

a = '"qwerty" "uiop"'
# if the quotes occur at beginning and end
a = a.strip('\"')
print(a)
# if they only occur at beginning
a = a.lstrip('\"')
print(a)
# if the quotes occur at the end
a = a.rstrip('\"')
print(a)

Output

qwerty" "uiop
qwerty" "uiop
qwerty" "uiop

Here, the code removes the quotes from the string. These quotes may occur at the start, end or both. For quotes occurring at the beginning and the end, the strip('\"') is used for removing them. The escape character \ is used. For quotes occurring at the beginning, the lstrip('\"') to remove them.

The rstrip('\"') method is used for removing the quotes that occur at the end.

What If python Strip() Does Not Work?

There may be a case where you will notice that the strip() method does not work. Check out this example:

Example

sentence = "Hello There!"
print(sentence)
print(sentence.strip())

Output

Hello There!
Hello There!

Some users might complain that the strip() method is not working and not removing the whitespaces. You can see that the outputs are the same with and without using the strip() function. This is because strip() method removes whitespaces from the beginning and end of a string when no arguments are passed. In this case, no arguments are passed to the method, but there are no whitespaces in the string.

As a result, strip() does not find anything to remove and returns the string just as it was before. If the string would have been " Hello There! ", strip() would have removed the whitespaces.

You can use rstrip() or lstrip() to remove leading or trailing whitespaces. Additionally, you can use the replace() method to remove whitespaces, like this:

sentence.replace(" ", "")

Conclusion

The strip() method is very useful and its types rstrip() and lstrip() can also be used to remove unwanted spaces and characters from strings. But make sure your string has whitespaces in it for the method to remove. Also, remember that strip() only accepts strings as arguments, so passing an integer will throw an error. 


×