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
| 1234567891011121314151617181920212223242526272829303132333435363738 |
>>> u = "www.doiido.com.cn" #使用默认分隔符>>> print u.split()[‘www.doiido.com.cn‘] #以"."为分隔符>>> print u.split(‘.‘)[‘www‘, ‘doiido‘, ‘com‘, ‘cn‘] #分割0次>>> print u.split(‘.‘,0)[‘www.doiido.com.cn‘] #分割一次>>> print u.split(‘.‘,1)[‘www‘, ‘doiido.com.cn‘] #分割两次>>> print u.split(‘.‘,2)[‘www‘, ‘doiido‘, ‘com.cn‘] #分割两次,并取序列为1的项>>> print u.split(‘.‘,2)[1]doiido #分割最多次(实际与不加num参数相同)>>> print u.split(‘.‘,-1)[‘www‘, ‘doiido‘, ‘com‘, ‘cn‘] #分割两次,并把分割后的三个部分保存到三个文件>>> u1,u2,u3 = u.split(‘.‘,2)>>> print u1www>>> print u2doiido>>> print u3com.cn |
2. Remove newline characters
?
| 1234567891011 |
>>> C = "' Say hello baby "   >> > print c say hello baby >>> print c.split ( ) [ ' say ' ' hello ' ' baby ' |
3. Separating the file name and path
?
| 12345 |
>>> import os Code class= "Py Plain" >>>> print Os.path.split ( '/dodo/soft/python/' ) ( '/dodo/soft/python ' , ") Code class= "Py Plain" >>>> print Os.path.split ( '/dodo/soft/python ' ) ( '/dodo/soft ' ' python ' ) |
4, a Super good example
?
| 1234567 |
>>> str="hello boy<[www.doiido.com]>byebye" >>> print str.split("[")[1].split("]")[0]www.doiido.com >>> print str.split("[")[1].split("]")[0].split(".")[‘www‘, ‘doiido‘, ‘com‘] |
Python function split ()