1. Using multiple characters or strings as separators to split a string
The Str.split () method can only make a single character or string as a delimiter, and the Re.split () method may use the regular expression as the delimiter, Re.split () is the same as the Str.split () return value type;
1 ' asdf fjdk; afed, FJEK,ASDF, foo ' 2 Import Re 3 >>> re.split (R'[;, \s]\s*', line)4# out : [' asdf ', ' fjdk ', ' afed ', ' Fjek ', ' asdf ', ' foo ']
2. Check whether the beginning or end is a specified string
Check the beginning of the string can be used Str.startswith (), the end can be used Str.endswith ();
1>>> filename ='Spam.txt'2>>> Filename.endswith ('. txt')3 #out:true4>>> Filename.startswith ('File:')5 #Out:false6>>> URL ='http://www.python.org'7>>> Url.startswith ('http:')8 #out:true
To match multiple possibilities, multiple matches can be packaged in tuples and then passed into the function;
1>>>ImportOS2>>> filenames = Os.listdir ('.')3>>>Filenames4 #Out : [' Makefile ', ' foo.c ', ' bar.py ', ' spam.c ', ' spam.h ']5>>> [Name forNameinchFilenamesifName.endswith (('. C','. h'))]6 #Out : [' foo.c ', ' spam.c ', ' spam.h '
You can also use slices to achieve, but it is not so elegant;
1 ' Spam.txt ' 2 ' . txt ' 3 # out:true
Match multiple suspicious uses or;
3. String substitution
Simple string substitution can be used:Str.repalce (), complex point with the sub () function in the RE module;
Python Techniques for string handling