前言
Python版本:3.7.4
split(pattern, string, maxsplit=0, flags=0)
-
原文
-
Split the source string by the occurrences of the pattern,
returning a list containing the resulting substrings. If
capturing parentheses are used in pattern, then the text of all
groups in the pattern are also returned as part of the resulting
list. If maxsplit is nonzero, at most maxsplit splits occur,
and the remainder of the string is returned as the final element
of the list.
就是
-
根据pattern分割文本
当使用【捕捉括号】时,所有组都会返回
maxsplit限制最大切割次数,默认无限切
最终返回list
一般情况
from re import split
a = split(',', 'aa,bb')
print(a)
['aa', 'bb']
限制切割次数
from re import split
a = split(',', 'aa,bb,cc', 1)
print(a)
['aa', 'bb,cc']
结果出现’’
from re import split
a = split(',', ',aa,,bb,')
print(a)
['', 'aa', '', 'bb', '']
pattern使用括号
from re import split
a = split('(,)', 'aa,')
print(a)
['aa', ',', '']
pattern使用多重括号
from re import split
a = split('aa(bb(cc))', 'ZaabbccZ')
print(a)
['Z', 'bbcc', 'cc', 'Z']
patter同时用 () 和 | 会出现None
from re import split
a = split(',|(;)', 'aa,bb;cc')
print(a)
['aa', None, 'bb', ';', 'cc']
排除空值的写法
from re import split
a = [i for i in split(',|(;)', ',aa,;bb,')if i]
print(a)
['aa', ';', 'bb']
本文详细介绍了Python中re模块的split函数用法,包括基本使用、限制切割次数、处理空值及特殊字符,展示了如何通过正则表达式进行字符串分割,并提供了排除空值的代码示例。
2万+

被折叠的 条评论
为什么被折叠?



