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"]
0

3 Answers 3

10

You may simply specify a number of splits:

s.split(' ', 4)
Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

1

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

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.