python split 多个分隔符_正则表达式-python:split的用法(Modifying a string)

正则表达式-python:split的用法

在python种split的作用:修改字符串(Modifying a string)

In almost every language, you can find the split operation in strings.

在python3中使用split特别注意两点:

  • 正则表达式(pattern)带不带括号的区别
  • 第一个字符就与正则表达式匹配,结果中的第一个位置会包含一个空字符(Note that when a group matches the start of the string, the result will contain the empty string as a first result.)

正则表达式(pattern)带不带括号的区别

386801f6a88b0bea3a1fcec24ab6a0d0.png

第一个字符就与正则表达式匹配

5c0c07f74c6fb39f25a018dd1c15f297.png

参数maxsplit的用法:

eb7caecd9e3553ad063834af7a5cd9bd.png

需要多个分隔符时用中括号[]

e370e3b9340adfba10c9081a6f4095a5.png

最后附上所有源码:

Modifying a string

  • In almost every language, you can find the split operation in strings.
import re
  • Note that when a group matches the start of the string, the result will contain the empty string as a first result:
re.split(r"n", "Beautiful is better than ugly.nExplicit is better than implicit.")
['Beautiful is better than ugly.', 'Explicit is better than implicit.']
re.split(r"(n)", "Beautiful is better than ugly.nExplicit is better than implicit.")
['Beautiful is better than ugly.', 'n', 'Explicit is better than implicit.']
pattern = re.compile(r"(-)") #注意此处的括号,与groups有关
pattern.split("-hello-word")
['', '-', 'hello', '-', 'word']
pattern = re.compile(r"(-)") #注意此处的括号,与groups有关
pattern.split("hello-word")
['hello', '-', 'word']
pattern = re.compile(r"W")
pattern.split("Beautiful is better than ugly", 2) 
#The maxsplit parameter specifies how many splits can be done at maximum
['Beautiful', 'is', 'better than ugly']
pattern = re.compile(r"W")
pattern.split("Beautiful is better than ugly") 
#The maxsplit parameter specifies how many splits can be done at maximum
['Beautiful', 'is', 'better', 'than', 'ugly']
pattern = re.compile(r"(W)")
pattern.split("⇢hello⇢word")
['', '⇢', 'hello', '⇢', 'word']
pattern = re.compile(r"([W,l])")
pattern.split("⇢hello⇢word")
['', '⇢', 'he', 'l', '', 'l', 'o', '⇢', 'word']
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值