0

For example, I have a string section 213(d)-456(c)

How can I split it to get a list of strings:

['section', '213', '(', 'd', ')', '-', '456', '(', 'c', ')'].

Thank you!

2 Answers 2

2

You can do so using Regex.

import re
text = "section 213(d)-456(c)"
output = re.split("(\W)", text)

Output: ['section', ' ', '213', '(', 'd', ')', '', '-', '456', '(', 'c', ')', '']

Here \W is for non-word character!

Sign up to request clarification or add additional context in comments.

Comments

0

You can come close with

re.split(r'([-\s()])', 'section 213(d)-456(c)')

When the delimiter contains a capture group, the result includes the captured text.

However, this will also include the space delimiters in the result:

['section', ' ', '213', '(', 'd', ')', '', '-', '456', '(', 'c', ')', '']

You can easily remove these afterward.

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.