简体   繁体   中英

maxsplit functionality for regex split

I have a string like this

aa = 'nilesh-sharma-is-learning-python'

Now I want to split this string for - delimiter and with max_split 3 times. It can be easily do like this

In [35]: aa.split('-',3)
Out[35]: ['nilesh', 'sharma', 'is', 'learning-python']

Using regex also we can split the string

In [36]: re.split('-',aa)
Out[36]: ['nilesh', 'sharma', 'is', 'learning', 'python']

How can I implement max_split functionality in case of regex split ?

According to the Docs , you can provide a maxsplit argument also. (3rd argument, or keyword maxsplit .

>>> import re
>>> aa = 'nilesh-sharma-is-learning-python'
>>> re.split('-', aa, maxsplit=3)
['nilesh', 'sharma', 'is', 'learning-python']
>>> 

https://docs.python.org/3/library/re.html#re.split

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM