This article mainly introduces you to seven techniques for learning Python string processing, including string concatenation and merging, string slicing and multiplication, string division, and the beginning and end of strings. Friends who need it can refer to operations such as processing, searching and matching of strings, replacing strings, and removing some characters from strings.
Preface
Daily use of python often requires text processing, whether it is crawler data analysis, big data text cleaning, or Ordinary file processing requires the use of strings. Python has many built-in efficient functions for string processing, which are very convenient and powerful. Here are 7 commonly used tricks that I have summarized. With these tricks, you can easily Dealing with string processing.
1. String concatenation and merging
##Connection and merging
Add //Two strings can be easily connected through '+' Merge //Use the join method
2. String slicing and multiplication
Multiplication//For example, when writing code, it is easy to use delimiters when using python Implementline='*'*30 print(line) >>******************************
Slicing
3. String Split
Ordinary splitting, using split
split can only do very simple splitting, and does not support multiple splitsphone='400-800-800-1234' print(phone.split('-')) >>['400', '800', '800', '1234']
Complex splitting
r means no escaping, the delimiter can be; or, or a space followed by 0 or more extra Space, and then split according to this pattern4. Processing of the beginning and end of the string
For example, we want to check what the name of a file begins or ends withfilename='trace.h' print(filename.endswith('h')) >>True print(filename.startswith('trace')) >>True
5. Searching and matching strings
General search
We can easily search for substrings in long strings, and the index of the location of the substring will be returned. If found Not returning -1Complex match
6. Replacement of strings
Ordinary replacement // Just use replace Complex replacement // To handle For complex or multiple replacements, you need to use the sub function of the re module## 7. Remove some characters from the stringRemove spaces //When processing text, for example, reading a line from a file, then you need to remove spaces, tables or newline characters on both sides of each line
line=' Congratulations, you guessed it. ' print(line.strip()) >>Congratulations, you guessed it.
Note:The spaces inside the string cannot be removed. If you want to remove it, you need to use the re moduleFor complex text cleaning, you can use
str.translate,First build a conversion table. The table is a translation table, which means converting 't''o' into uppercase 'T' 'O',
Then remove '12345' from old_str, and then the remaining string is translated through table
##SummaryThe above is the detailed content of Teach you seven techniques for Python string processing. For more information, please follow other related articles on the PHP Chinese website!