This article mainly introduces seven techniques for learning Python string processing, including the connection and merging of strings, slicing and multiplying of strings, splitting of strings, processing of the beginning and end of strings, searching and matching of strings, substitution of strings, and removal of some characters from strings. You need a friend to refer to.
Objective
Daily use of Python often to deal with the text, whether it is the data analysis of the reptile, or the big data of the text cleaning, or ordinary file processing, is to use the string. Python has a lot of efficient functions built into string processing, which is very handy and powerful. Here are some of the 7 common tricks I've summed up, and it's easy to deal with string processing with these tips.
I. Connection and merging of strings
Connect and Merge
Add//Two strings can be easily connected by ' + '.
Merge//With Join method
Second, slicing and multiplying of strings
Multiply//For example, when writing code, the delimiter is easy to implement with Python.
Line= ' * ' *30print (line) >>******************************
Slice
Three, the segmentation of the string
Ordinary split, with split
Split can only be very simple to split, and does not support multiple separators
Phone= ' 400-800-800-1234 ' Print (Phone.split ('-')) >>[' 400 ', ' 800 ', ' 800 ', ' 1234 ']
Complex segmentation
R means no escaping, the delimiter can be, or, a space followed by 0 additional spaces, and then the pattern to split
Iv. handling of the beginning and end of a string
For example, we're going to find out what the name of a file is, what it starts with or what ends.
Filename= ' trace.h ' Print (Filename.endswith (' h ')) >>trueprint (Filename.startswith (' trace ')) >>true
V. Finding and matching strings
General Search
We can easily find substrings in a long string, and return the index where the substring is located, if it cannot find the return-1
A complex match
Vi. Substitution of strings
Normal replacement//with replace can be
Complex substitution//to handle complex or multiple substitutions, you need to use the sub function of the RE module
Seven, remove some characters from the string
Remove space//For text processing such as reading a line from a file, and then need to remove the space on either side of each line, table or line break
Line= ' Congratulations, you guessed it. ' Print (Line.strip ()) >>congratulations, you guessed it.
Note: The space inside the string cannot be removed, to remove the need to use the RE module
Complex text cleanup that can be exploited str.translate
,
First build a conversion table, table is a translation table, indicating the ' t ' o ' turn into uppercase ' t ' o ',
Then remove ' 12345 ' from the Old_str, then the remaining strings are translated by the table.
Summarize