strip() method in Python

strip() removes leading and trailing characters of a string as specified in the parameter and returns a copy of the string.

Str Updated 15 Mar 2017 1 min read

Method Name

strip

Method Signature

strip([charsToRemove])

Method Overview

  • strip() removes leading, trailing characters as specified in the parameter charsToRemove and returns a new string object.

  • Each character in the charsToRemove parameter is compared against the beginning of the string. If the characters match then the character is removed. Else the algorithm stops and continues from the trailing end of the string.

  • Each character in the charsToRemove parameter is compared against the trailing end of the string.

  • If the characters match then the character is removed. Else the algorithm stops and the new string object that has the leading and trailing characters removed as per the specification is returned.

  • If no single character has been removed from the string, the same string object is returned.

Example

python
consoleOutput = "=======>Results Display<======="

rawString       = consoleOutput.strip("=><")

print(consoleOutput)

print(rawString)

plainString = "Universe"

noDecor     = plainString.strip(",#=*&")

print(noDecor)

print("Id of plainString:%s"%(id(plainString)))

print("Id of noDecor:%s"%(id(noDecor)))

Output

Output
Results Display

Universe

Id of plainString:4302757680

Id of noDecor:4302757680