re函数split各种情况

本文详细介绍了Python中re模块的split函数用法,包括基本使用、限制切割次数、处理空值及特殊字符,展示了如何通过正则表达式进行字符串分割,并提供了排除空值的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小基基o_O

您的鼓励是我创作的巨大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值