Detailed usage of strip (), lstrip (), and rstrip () in Python, and lstriprstrip

Source: Internet
Author: User

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'

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.