re函数split各种情况

Badia ·
更新时间:2024-11-10
· 524 次阅读

文章目录前言一般情况限制切割次数结果出现''pattern使用括号pattern使用多重括号patter同时用 () 和 | 会出现None排除空值的写法 前言

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


作者:基基伟



split

需要 登录 后方可回复, 如果你还没有账号请 注册新账号