How to Remove spaces at both ends of a string using Python

Source: Internet
Author: User
This article describes how to remove spaces at both ends of a string in Python. This article describes how to use string. lstrip, string. rstrip, string. strip, and other functions. For more information, see Purpose

Returns a string with no leading or trailing spaces.

Method

You can use the following methods of string processing:

String. lstrip (s [, chars])
Return a copy of the string with leading characters removed. if chars is omitted or None, whitespace characters are removed. if given and not None, chars must be a string; the characters in the string will be stripped from the beginning of the string this method is called on.

String. rstrip (s [, chars])
Return a copy of the string with trailing characters removed. if chars is omitted or None, whitespace characters are removed. if given and not None, chars must be a string; the characters in the string will be stripped from the end of the string this method is called on.

String. strip (s [, chars])
Return a copy of the string with leading and trailing characters removed. if chars is omitted or None, whitespace characters are removed. if given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.

The specific effect is as follows:

The code is as follows:


In [10]: x = 'Hi, Jack! '

In [11]: print '|', x. lstrip (), '|', x. rstrip (), '|', x. strip (), '|'
| Hi, Jack! | Hi, Jack! | Hi, Jack! |

The chars parameter is used to delete a specific symbol. Note that spaces are not removed. for example:

The code is as follows:


In [12]: x = 'xyxyxxxyy Hello xyxyxyxyy'

In [13]: print x. strip ('XY ')
Hello

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.