Python methods for removing whitespace at both ends of a string

Source: Internet
Author: User
Purpose

Get a string that contains no extra 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, the whitespace characters is removed. If given and not None, chars must is a string; The characters in the string would 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, the whitespace characters is removed. If given and not None, chars must is a string; The characters in the string would be stripped from the end of the "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, the whitespace characters is removed. If given and not None, chars must is a string; The characters in the string would be stripped from the both ends of the string this method is called on.

The specific results are as follows:

The code is as follows:


In [ten]: x= ' hi,jack! '

In [all]: print ' | ', X.lstrip (), ' | ', X.rstrip (), ' | ', X.strip (), ' | '
| hi,jack! | hi,jack! | hi,jack! |

The parameters provided by chars are used to remove specific symbols, noting that the spaces are not removed, for example:

The code is as follows:


In []: x= ' yxyxyxxxyy Hello xyxyxyy '

In []: 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.