Usage of split() function in Python3

One, split() function

1. Grammar:

str.split(str="",num=string.count(str))[n]
1
str: expressed as a separator. The default is all empty characters, including spaces, newlines (\n), tabs (\t), etc., but they cannot be empty (''). If there is no separator in the string, the entire string is regarded as an element of the list.
num: indicates the number of divisions. The default is -1, which means that all is separated. If the parameter num is present, it will only be separated into num+1 substrings, and each substring can be assigned to a new variable
[n]: the subscript in the selected split list is Fragmentation of n
Return value: Return a list of the divided strings.

2. Separate strings

str = “www.csdn.net”

2.1. Use'.' as the separator

print(str.split(’.’))

[‘www’, ‘csdn’, ‘net’]

2.2. Split once

print(str.split(’.’,1))

[‘www’, ‘csdn.net’]

2.3. Divide twice and take the item whose sequence is 1

print(str.split(’.’,2)[1])

csdn

2.4. Split twice, and save the three parts after splitting to three files

s1, s2, s3 =str.split(’.’,2)

print(s1) >>> www

print(s2) >>> csdn

print(s3) >>> net

Two, os.path.split() function

1. Grammar:

os.path.split('PATH')
1
1.PATH refers to the full path of a file as a parameter:

2. If given is a directory and file name, output the path and file name

3. If a directory name is given, the output path and empty file name

2. Separate file name and path

import them

print(os.path.split(’/d/soft/python/’))

(’/d/soft/python’, ‘’)

print(os.path.split(’/d/soft/python’))

(’/d/soft’, ‘python’)

3. Example: Obtain a domain name

str=“hello csdn<[www.csdn.net]>byebye”

print(str.split("[")[1].split("]")[0])

www.csdn.net

When we are learning python crawler, for example, we need to save the picture and get the picture name according to the following methods:

url = “http://www.baidu.com/python3/image/123.jpg”
path =url.split("/")[-1]

Output result:
'123.jpg'
————————————————
Transfer from: https://blog.csdn.net/gxz987/article/details/90345811

Guess you like

Origin blog.csdn.net/Love_Polaris/article/details/103680178