Detailed usage of strip (), lstrip (), and rstrip () in Python, and lstriprstrip
Python has three functions to remove leading and trailing characters and spaces. They are:
Strip: used to remove leading and trailing characters and blank spaces (including \ n, \ r, \ t, '', that is, line breaks, carriage returns, tabs, and spaces)
Lstrip: used to remove the starting character and blank space (including \ n, \ r, \ t, '', that is, line feed, carriage return, tab, space)
Rstrip: Used to Remove trailing characters and blank spaces (including \ n, \ r, \ t, '', that is, line breaks, carriage returns, tabs, and spaces)
Note: These functions only Delete the first and last characters, but not the middle.
Usage:
String. strip ([chars])
String. lstrip ([chars])
String. rstrip ([chars])
The chars parameter is optional. If chars is empty, the blank spaces (including \ n, \ r, \ t, and '') at the beginning and end of the string are deleted by default ,'')
When chars is not empty, the function is interpreted as a character by chars, and the characters are removed.
It returns a string copy of the first and end characters (or blank characters), and the string itself will not change.
Example:
1. When chars is empty, blank spaces (including '\ n',' \ R', '\ t', '') are deleted by default ','')
>>> Str = 'AB Cd' >>> str. strip () # Remove leading and trailing spaces 'AB Cd'> str. lstrip () # Delete the leading space 'AB Cd'> str. rstrip () # Delete the Ending Space 'AB Cd'
2. When chars is not empty, the function is parsed into characters by chars, and the characters are removed.
>>> Str2 = '1a2b12c21 '>>> str2.strip ('12') # Delete the first and second 'a2b12c' >>> str2.lstrip ('12 ') # Delete the first 1 and 2 'a2b12c21 '>>> str2.rstrip ('12') # delete the end 1 and 2 '1a2b12c'