Python知识精解:str split()方法

描述

split()函数是Python字符串函数。split() 通过指定分隔符对字符串进行切片。如果指定了整型参数num,则仅分隔num + 1个子字符串(即分割num次)。使用split()函数将字符串分割后,返回的是一个列表,列表中存储着分割后的每个子串。

语法及参数

str.split(string, num)

实例

1. 所有参数都省略

s = 'Hello world!'
d = s.split()
print(d)

输出结果为:

['Hello', 'world!']

2. 仅指定分隔符

s = 'Hello world! I am Python&I am not Java!'
d = s.split('&')
print(d)

输出结果为:

['Hello world! I am Python', 'I am not Java!']

3. 指定分隔符和分割次数

s = 'I am Python&I am not Java!&Python is Interesting'
d = s.split('&', 1)
print(d)

输出结果为:

['I am Python', 'I am not Java!&Python is Interesting']

注意事项

1. 使用split()后,有效分隔符不会存在于任何子串中。

有效分隔符:待分割的字符串中存在该分隔符,且num参数有效。

>>> s = "list&index&out&of&range"
>>> s_l = s.split("&")
>>> s_l.count("&")
0
>>> s_l
['list', 'index', 'out', 'of', 'range']

2. 使用空字符串作为分隔符时,Python会报错

当使用空字符串作为分隔符时,Python会抛出ValueError。

>>> demo = "a, b, c, d"
>>> demo.split("")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: empty separator

觉得有用的同学可以点下赞同呀~

关注我,获得更多技术知识~

发布于 2020-02-24 17:45