Function: Split ()
There are two functions for split () and Os.path.split () in Python, as follows:
Split (): Splits the string. Slices a string by specifying a delimiter and returns a segmented list of strings
Os.path.split (): Splits the file name and path by path
First, function description
1. Split () function
Syntax: Str.split (str= "", Num=string.count (str)) [n]
Parameter description:
STR: is represented as a delimiter, the default is a space, but cannot be empty ('). If there is no delimiter in the string, the entire string is used as an element of the list
Num: Indicates the number of splits. If there is a parameter num, it is separated into only num+1 substrings, and each substring can be assigned to a new variable
[n]: Indicates selection of Nth Shard
Note: When spaces are used as separators, items that are empty in the middle are automatically ignored
2. Os.path.split () function
Syntax: Os.path.split (' path ')
Parameter description:
- Path refers to the full path of a file as a parameter:
- If a directory and filename are given, the output path and file name
- If a directory name is given, the output path and the empty file name
Second, examples
1. Common examples
1>>> U ="www.doiido.com.cn"2 3 #Use default delimiter4>>>PrintU.split ()5['www.doiido.com.cn']6 7 #with "." As a delimiter8>>>PrintU.split ('.')9['www','Doiido','com','cn']Ten One #Split 0 Times A>>>PrintU.split ('.', 0) -['www.doiido.com.cn'] - the #Split once ->>>PrintU.split ('.', 1) -['www','doiido.com.cn'] - + #split two times ->>>PrintU.split ('.', 2) +['www','Doiido','com.cn'] A at #split two times and take a sequence of 1 items ->>>PrintU.split ('.', 2) [1] - Doiido - - #split most times (actually same as no num parameter) ->>>PrintU.split ('.',-1) in['www','Doiido','com','cn'] - to #split two times and save the divided three sections to three files +>>> U1,U2,U3 = U.split ('.', 2) ->>>PrintU1 the www *>>>PrintU2 $ DoiidoPanax Notoginseng>>>PrintU3 -com.cn
2. Remove newline characters
" " Sayhellobaby "" Print Csayhellobaby print c.split ('\ n') ['say' ' Hello ' ' Baby ']
3. Separating the file name and path
>>>ImportOS>>>PrintOs.path.split ('/dodo/soft/python/')('/dodo/soft/python',"')>>>PrintOs.path.split ('/dodo/soft/python')('/dodo/soft','python')
4, a Super good example
>>> str="Hello Boy<[www.doiido.com]>byebye">>>PrintStr.split ("[") [1].split ("]") [0]www.doiido.com>>>PrintStr.split ("[") [1].split ("]") [0].split (".")['www','Doiido','com']
Reprinted from: http://www.jb51.net/article/63592.htm
How to use the split () function in Python