The Python Strip Function

The Python programming language provides a host of libraries and functions with which a programmer can easily perform mundane or common tasks. Since many Python programs require the manipulation of strings as input or output, various methods inside Python work on string objects. One of these methods, the "strip()" method, removes characters from a string.

  1. Basic "strip()" functionality

    • The "strip()" function returns a copy of a string with certain characters removed from the beginning and end of the string. Essentially, the strip function checks the beginning and end characters against a user-defined set of characters, and deletes them until running into a non-matching character. The following code is a simple example.

      >>>s = 'wwwthisisasstringooo'

      >>>s.strip('w')

      'thisisastringooo'

      >>>s.strip('o')

      'wwwthisisastring'

      >>>s.strip('wo')

      'thisisastring'

    The "lstrip()" and "rstrip()" Methods

    • The strip method works on both ends of the string. However, to strip characters from only the front or rear of the string, use "lstrip()" (for the beginning of the string) and "rstrip()" (for the end of the string). The following code shows an example of removing character from only one end of the string.

      >>>s.lstrip('w')

      'thisisastringooo'

      >>>s.lstrip('o')

      wwwthisisastringooo

      >>>s.rstrip('o')

      'wwwthisisastring'

    Example: Stripping HTML tags

    • For another example, a Python programmer might want to strip HTML tags from information retrieved from a Web page. The HTML strings would be enclosed in HTML tags, but the programmer might only need the actual data. In this case, using the strip command can make removing tags easier.

      >>>html = '<html>Hello</html>'

      >>>html.strip('<html></html>')

      'Hello'

      >>>html = '<html><body>Hello</body></html>'

      >>>html.strip('<html><body></body></html>')

      'Hello'

    Trimming Whitespace

    • In another example, user input, or input gathered from the Web, might contain leading white space (such as spaces or tabs). The strip function can also trim up white space characters as easily as it can any other character.

      >>>s = ' hi '

      >>>s.strip(' ')

      'hi'

      >>>s.lstrip(' ')

      'hi '

Related Searches:

References

Comments

Related Ads

Featured