简体   繁体   English

正则表达式拆分的 maxsplit 功能

[英]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.现在我想将此字符串拆分为-分隔符和max_split 3 次。 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 ?在 regex split 的情况下如何实现max_split功能?

According to the Docs , you can provide a maxsplit argument also.根据Docs ,您也可以提供maxsplit参数。 (3rd argument, or keyword maxsplit . (第三个参数,或关键字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 https://docs.python.org/3/library/re.html#re.split

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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