Delete unnecessary characters from the string
You want to remove the beginning of the text string , An unwanted character at the end or in the middle , For example, blank
strip() Method can be used to delete the beginning or end of the character . lstrip() and rstrip() Delete from left and right respectively . By default , These methods remove white space characters , But you can also specify other characters . such as ：
# Whitespace stripping > s = ' hello world \n' > s.strip() 'hello world' > s.lstrip() 'hello world \n' > s.rstrip() ' hello world' > >>> # Character stripping > t = '-----hello=====' > t.lstrip('-') 'hello=====' > t.strip('-=') 'hello' >>
these strip() Methods are often used to read and clean data for subsequent processing . such as , You can use them to remove spaces , Quotation marks and other tasks .
However, it should be noted that the removal operation does not have any effect on the text in the middle of the string . such as ：
' hello world \n' > s = s.strip() > s 'hello world' >> s =
If you want to deal with spaces in the middle , So you need to turn to other technologies . For example, use replace() Methods or replace with regular expressions . Examples are as follows ：
' ', '') 'helloworld' > import re > re.sub('\s+', ' ', s) 'hello world' >> s.replace(
Usually you want to put the string strip Operations are combined with other iterative operations , For example, read multiple lines of data from a file . If so , Then the generator expression will be able to show its skill . such as ：
with open(filename) as f: lines = (line.strip() for line in f) for line in lines: print(line)
ad locum , expression lines = (line.strip() for line in f) Perform data conversion operations . It's very efficient , Because it doesn't need to read all the data in advance and put it in a temporary list . It just creates a generator , And every time the line is returned, it will execute strip operation .
For higher order strip, You may need to use translate() Method .