Python regular expression split() string

Question:

I’m quite new to regular expressions in Python. I have the following string and want to split them into five categories. I just use the split(), but it will just split according to white spaces.

s = "1 0 A10B 1/00 Description: This is description with spaces"
sp = s.split()
>>> sp
["1", "0", "A10B", "1/00", "Description:", "This", "is", "description", "with", "spaces"]

How can I write a regular expression to make it split like the following?

 ["1", "0", "A10B", "1/00", "Description: This is description with spaces"]
Asked By: hash__x

||

Answers:

You may simply specify a number of splits:

s.split(' ', 4)
Answered By: Roman Bodnarchuk

Not a perfect solution. But for a start.

>>> sp=s.split()[0:4]
>>> sp.append(' '.join(s.split()[4:]))
>>> print sp
['1', '0', 'A10B', '1/00', 'Description: This is description with spaces']
Answered By: tuxuday

The second argument to split() is the maximum number of splits to perform. If you set this to 4, the remaining string will be item 5 in the list.

 sp = s.split(' ', 4)
Answered By: cytinus
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.