split():拆分字符串。针对字符串中包含相同符号,可以进行一次或多次切割
#使用默认分隔符
>>> s = "https://www.baidu.com/"
>>> s
'https://www.baidu.com/'
>>> s.split()
['https://www.baidu.com/']
#以"."为分隔符
>>> s.split('.')
['https://www', 'baidu', 'com/']
#分割0次
>>> s.split('.', 0)
['https://www.baidu.com/']
#分割一次
>>> s.split('.', 1)
['https://www', 'baidu.com/']
#分割两次
>>> s.split('.', 2)
['https://www', 'baidu', 'com/']
#分割两次,并取序列为1的项
>>> s.split('.', 2)[1]
'baidu'
#分割最多次(实际与不加num参数相同)
>>> s.split('.', -1)
['https://www', 'baidu', 'com/']
#分割两次,并把分割后的三个部分保存到三个文件。文件个数与切割后项的数量保持一致,不然会报错
>>> t1, t2 = s.split('.')
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
t1, t2 = s.split('.')
ValueError: too many values to unpack (expected 2)
>>> t1, t2, t3, t4 = s.split('.')
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
t1, t2, t3, t4 = s.split('.')
ValueError: not enough values to unpack (expected 4, got 3)
>>> t1, t2, t3 = s.split('.')
>>> t1
'https://www'
>>> t2
'baidu'
>>> t3
'com/'