How can I split a string on every third space? I'm wondering if python has built-in syntax for this or if it can be done using a list comprehension.
"a bb c dd ee f" -> ["a bb c", "dd ee f"]
re.split(r'(.*?\s.*?\s.*?)\s', "a bb c dd ee f")
为了从结果中删除空字符串:
[x for x in re.split(r'(.*?\s.*?\s.*?)\s', "a bb c dd ee f") if x]
As a more general way you can use a function :
>>> def spliter(s,spl,ind):
... indx=[i for i,j in enumerate(s) if j==spl][ind-1]
... return [s[:indx],s[indx+1:]]
...
>>> s="a bb c dd ee f"
>>> spliter(s,' ',3)
['a bb c', 'dd ee f']
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.