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