The super easy-to-use split() function in Python, detailed explanation


1. Introduction to split function

The split() function in Python has the following specific functions:

  • Split the string. Slice the string by specifying the delimiter and return the split string list (list);

2. Grammar

split() method syntax:

str.split(str="",num=string.count(str))[n]

Parameter description:
str : expressed as a separator, the default is a space, but it cannot be empty (''). If there is no delimiter in the string, the entire string is treated as an element of the list
num : represents the number of divisions. If the parameter num is present, it is only divided into num+1 substrings, and each substring can be assigned to a new variable. The default is -1, which separates everything.
[n] : Indicates selecting the nth shard

Note: When using spaces as separators, empty items in the middle will be automatically ignored.

3. Separate strings

string = “www.gziscas.com.cn”

1. Use ' . ' as the delimiter

print(string.split('.'))

Output:

['www', 'gziscas', 'com', 'cn']

2. Divide twice

print(string.split('.',2))

Output:

['www', 'gziscas', 'com.cn']

3. Divide twice and take the item with sequence 1

print(string.split('.',2)[1])

Output:

gziscas

4. Split it twice and save the divided 3 parts to 3 files

u1, u2, u3 =string.split('.',2)

print(u1)   #输出:www
print(u2)   #输出:gziscas
print(u3)   #输出:com.cn

Output:

www
gziscas
com.cn

4. Examples

str="hello boy<[www.baidu.com]>byebye"

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

Output:

www.baidu.com

analyze:

  1. First execute str.split("[")[1], the result is: www.baidu.com]>byebye
  2. Execute again: "www.baidu.com]>byebye".split("]")[0], the result is: "www.baidu.com"
  3. The final print output result: www.baidu.com

Guess you like

Origin blog.csdn.net/weixin_44793743/article/details/126572303