re函数split各种情况

前言

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']

猜你喜欢

转载自blog.csdn.net/Yellow_python/article/details/104640643