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"]
Answers:
You may simply specify a number of splits:
s.split(' ', 4)
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']
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)
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"]
You may simply specify a number of splits:
s.split(' ', 4)
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']
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)