Python str.split 和 re.split(), 多个分隔符情况

split适用于单个分隔符
当需要多个分隔时,可以逐次使用split()
text = "abc def!"
sg = text.split()
sg[1] = sg[1].split('!')[0]
print(sg) #['abc', 'def']
这种情况下,使用re.split()较为方便
re.split(pattern, string, maxsplit=0) #原型
re.split()的使用有两种方式:
re.split("[ !]", text) #[]里边放的是需要的分隔符,中间没有空格和逗号
re.split(",|!", text) #中间用 | 隔开
当是多个单一分隔符时,适合用第一种,第二种需要考虑某些字符需要转义使用
re.split("[;,?]")
re.split(";|,|\?", text)
当多个长短不一的分隔符时,适合第二种
re.split(r";|,|\?\s|;\s|,\s", text) 
text = "abc,l def!"
re.split("[, !]", text) #['abc', 'l', 'def','']
re.split(",| |!", text) #['abc', 'l', 'def','']
两个的结果最终是一样的
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值