How To Use String Truncation Function strip(), lstrip(), And rstrip() In Python3

There are three functions in Python to remove one string’s head and tail characters and the blank characters, they are strip, lstrip and rstrip.

  1. strip : Used to remove both head and tail characters and blank characters (includes \n, \r, \t,’   ‘).
  2. lstrip : Used to remove head characters and blank characters (includes \n, \r, \t,’   ‘).
  3. rstrip : Used to remove tail characters and blank characters (includes \n, \r, \t,’   ‘).
  4. Literally, r=right, l=left. strip, rstrip, lstrip are commonly used string formatting methods in python development.
  5. Note: these functions delete only the leading and trailing characters, not the middle ones

1. strip, lstrip, rstrip Function Syntax.

string.strip([chars])
string.lstrip([chars])
string.rstrip([chars])

Parameter chars is optional. Return value is a copy of the string removes the leading or trailing characters (or white space), but the string itself do not change.

2. Example When chars Is Empty.

When chars is empty, the default action is to delete the string’s leading and trailing blank character (including \n, \r, \t, ‘”).

[email protected]:~$ python3
Python 3.7.1 (default, Dec 14 2018, 19:28:38) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> domain = ' www.code-learner.com '
>>> domain
' www.code-learner.com '
>>> domain.strip() # trip both header and tailor white space.
'www.code-learner.com'
>>> domain.lstrip() # remove header white space
'www.code-learner.com '
>>> domain.rstrip() # remove tailor white space
' www.code-learner.com'
>>> 

3. Example When chars Is Not Empty.

When chars is not empty, chars is treated as a list of characters. Whether or not the characters in the list will be deleted depends on whether or not the beginning and ending of the string contains the character in the chars list to be deleted. If the string’s beginning or ending contains the deleted character in the list, the character will be deleted.

>>> domain = '^&*  www.code-learner.com #@!'
>>> domain
'^&*  www.code-learner.com #@!'
>>> domain.strip('[email protected]#^&*')
'  www.code-learner.com '
>>> domain.lstrip('[email protected]#^&*')
'  www.code-learner.com #@!'
>>> domain.rstrip('^&*')
'^&*  www.code-learner.com #@!'
>>> domain.rstrip('[email protected]#')
'^&*  www.code-learner.com '
>>>