"Python Cookbook" "String and Text" 11. Remove unwanted characters from a string

Source: Internet
Author: User

Problem: Remove unwanted characters at the beginning, end, or middle of the string, for example, whitespace

Solution:

1. The character is removed at the beginning or end of the string: Str.strip ()

2. Remove characters from left or right start: Str.lstrip (), Str.rstrip ()

3. Remove characters in the middle of the string: Str.replace (), Re.sub ()

Python 3.4.0 (V3.4.0:04f714765c13, Mar, 19:24:06) [MSC v.1600 32bit (Intel)] on Win32type"Copyright","credits" or "license ()"  forMore information.>>> s='Hello world \ n'>>>S.strip ()'Hello World'>>>S.lstrip ()'Hello world \ n'>>>S.rstrip ()'Hello World'>>> t='----hello===='>>> T.lstrip ('-')'hello===='>>> T.rstrip ('=')'----Hello'>>> T.strip ('-=')'Hello'>>> s2='Hello world \ n'>>> S2.strip ()#does not work with the middle space'Hello World'>>> S2.replace (' ',"')'helloworld\n'>>>ImportRe>>> Re.sub ('\s+',' ', S2)'Hello World'>>> Re.sub ('\s+',"', S2)'HelloWorld'>>>

The common scenario is to combine the action of removing characters with some iterators, such as reading lines of text from a file. At this point, it's time for the generator expression to do its thing, for example:

With open ('test.txt') as F:    linesfor in  f)      for inch lines:         Print (line)
>>> ================================ RESTART ================================>>> Hello    Worldhello  Worldhello     World

The role of lines= (Line.strip () for lines in F) is to complete the conversion of the data, which is efficient because it does not first read the data into any form of a temporary list, it simply creates an iterator that performs the strip () operation on all the resulting lines of text.

For more advanced strip () operations, see the Translate () method in the next section.

"Python Cookbook" "String and Text" 11. Remove unwanted characters from a string

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.