POST
Python re module
re module is a unique string matching module of Python.
Many functions provided in this module are implemented based on regular expressions.
The module is handy, to use it, need to import re module at first.
prototype
re.split(pattern, string, maxsplit=0, flags=0)
parameters
pattern
: Separator, can be character or regular expression.string
: String to split.maxsplit
: Maximum number of split. default is 0, which means no limitation. if minus, means no split.flags
: Used to control how regular expressions are matched.
examples
- split the input string by
space
and,
, only do one time split.
import re
inputs = re.split(r'[\s,]+', input("Enter: 'ID' ['File name'] >> "), 1)
Enter: 'ID' ['File name'] >> 01 filename
inputs
['01', 'filename']
inputs = re.split(r'[\s,]+', input("Enter: 'ID' ['File name'] >> "), 1)
Enter: 'ID' ['File name'] >> 01,filename
inputs
['01', 'filename']
inputs = re.split(r'[\s,]+', input("Enter: 'ID' ['File name'] >> "), 1)
Enter: 'ID' ['File name'] >> 01,file1,file2 file3
inputs
['01', 'file1,file2 file3']
- split the string by character.
import re
s = 'ab12,% ffa[]-(fceknl)'
re.split(r'b',s)
['a', '12,% ffa[]-(fceknl)']
re.split(r'f',s)
['ab12,% ', '', 'a[]-(', 'ceknl)']
- match multiple characters
import re
s = 'ab12,% ffa[]-(fceknl)'
re.split(r'[1,en]',s)
['ab', '2', '% ffa[]-(fc', 'k', 'l)']
re.split(r'[-e(n]',s)
['ab12,% ffa[]', '', 'fc', 'k', 'l)']
- keep separator
import re
s = 'ab12,% ffa[]-(fceknl)'
re.split('([af])',s)
['', 'a', 'b12,% ', 'f', '', 'f', '', 'a', '[]-(', 'f', 'ceknl)']