1

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"]
1
  • you could do matching re.findall(r'\S+\s\S+\s\S+', "a bb c dd ee f") Commented Apr 13, 2015 at 19:43

2 Answers 2

5
re.split(r'(.*?\s.*?\s.*?)\s', "a bb c dd ee f")

and in order to remove empty strings from the result:

[x for x in re.split(r'(.*?\s.*?\s.*?)\s', "a bb c dd ee f") if x]
Sign up to request clarification or add additional context in comments.

2 Comments

You could also do re.split(r'(.*?\s.*?\s.*?)\s', "a bb c dd ee f")[1:]
@MattDMo true, but since this string is only an example, and in a real case there might be additional empty strings, I chose a more general approach (even if more verbose).
1

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.