The Python split of function splits strings and converts strings into columns
- 2021-07-22 10:01:29
- OfStack
Function: split ()
There are two functions in Python, split () and os. path. split (), which work as follows:
split (): Split the string. Slices a string by specifying a delimiter and returns a list of split strings (list)
os. path. split (): Separate file name and path by path
1. Function description
1. split () Function
Syntax: str. split (str= "", num=string. count (str)) [n]
Parameter description:
str: Represents as a delimiter, defaults to spaces, but cannot be empty (''). If there is no delimiter in the string, the whole string is regarded as 1 element of the list
num: Indicates the number of splits. If the parameter num exists, it is only separated into num+1 substrings, and every 1 substring can be assigned to a new variable
[n]: Selects the n fragment
Note: When a space is used as a delimiter, items with empty middle are automatically ignored
2. os. path. split () Function
Syntax: os. path. split ('PATH')
Parameter description:
PATH refers to the full path of 1 file as a parameter:
If 1 directory and file name are given, the path and file name are output
If 1 directory name is given, the output path and empty file name
2. Examples
1. Common examples
>>> u = "www.doiido.com.cn"
# Use the default separator
>>> print u.split()
['www.doiido.com.cn']
# With "." Is a separator
>>> print u.split('.')
['www', 'doiido', 'com', 'cn']
# Segmentation 0 Times
>>> print u.split('.',0)
['www.doiido.com.cn']
# Segmentation 1 Times
>>> print u.split('.',1)
['www', 'doiido.com.cn']
# Split twice
>>> print u.split('.',2)
['www', 'doiido', 'com.cn']
# Divide twice and take the sequence as 1 Items of
>>> print u.split('.',2)[1]
doiido
# Maximum number of splits (actual and non-added num Same parameters)
>>> print u.split('.',-1)
['www', 'doiido', 'com', 'cn']
# Split twice, and put the split 3 Parts are saved to 3 Files
>>> u1,u2,u3 = u.split('.',2)
>>> print u1
www
>>> print u2
doiido
>>> print u3
com.cn
2. Remove the line break
>>> c = '''say
hello
baby'''
>>> print c
say
hello
baby
>>> print c.split('\n')
['say', 'hello', 'baby']
3. Separate file name and path
>>> import os
>>> print os.path.split('/dodo/soft/python/')
('/dodo/soft/python', '')
>>> print os.path.split('/dodo/soft/python')
('/dodo/soft', 'python')
4, 1 Super Good 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']