An example illustrates the use of the split of function in Python
- 2020-05-07 19:54:16
- OfStack
Function: split ()
There are two functions in Python, split() and os.path.split (). The specific functions are as follows:
split() : split the string. Slice the string by specifying the delimiter and return a list of the split strings (list)
os.path.split () : split the file name and path by path
1. Function description
1, split() function
Grammar: str split (str = "", num = string count (str) [n]
Parameter description:
str: is represented as a separator, which defaults to a space, but cannot be empty ('). If there is no separator in the string, the entire string is used as one element in the list
num: number of cuts. If the parameter num exists, it is separated into only num+1 substrings, and each substring can be assigned to a new variable
[n] : means that the n shard is selected
Note: when Spaces are used as separators, items that are empty in the middle are automatically ignored
os.path.split() function
Grammar: os. path. split (' PATH)
Parameter description:
PATH refers to the full path of a file as a parameter: If a directory and file name are given, then output path and file name If a directory name is given, the output path and the empty file name are
2 instances
1
>>> u = "www.doiido.com.cn"
# Use the default delimiter
>>> print u.split()
['www.doiido.com.cn']
# In order to "." For the separator
>>> print u.split('.')
['www', 'doiido', 'com', 'cn']
# segmentation 0 time
>>> print u.split('.',0)
['www.doiido.com.cn']
# segmentation 1 time
>>> print u.split('.',1)
['www', 'doiido.com.cn']
# Division two
>>> print u.split('.',2)
['www', 'doiido', 'com.cn']
# Split twice, and take the sequence as 1 The item
>>> print u.split('.',2)[1]
doiido
# Split most times (actual and not added num Same parameter)
>>> print u.split('.',-1)
['www', 'doiido', 'com', 'cn']
# Divide it twice and divide it 3 Save the parts to 3 A file
>>> u1,u2,u3 = u.split('.',2)
>>> print u1
www
>>> print u2
doiido
>>> print u3
com.cn
2. Remove line breaks
>>> c = '''say
hello
baby'''
>>> print c
say
hello
baby
>>> print c.split('\n')
['say', 'hello', 'baby']
3. Separate file names and paths
>>> import os
>>> print os.path.split('/dodo/soft/python/')
('/dodo/soft/python', '')
>>> print os.path.split('/dodo/soft/python')
('/dodo/soft', 'python')
4. A great example
>>> 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']