0

I have a string like this =

str = (((MY (NAME IS) IS) YOUR NAME)

I want to split all the values in this string to get a result like this:

lst = ['(', '(', '(', 'MY', '(', 'NAME', 'IS', ')', 'IS', ')', 'YOUR', 'NAME', ')']

Is it possible to split the string like this with more than one delimiter?

2 Answers 2

7

You can use regex:

>>> import re
>>> s = '(((MY (NAME IS) IS) YOUR NAME)'
>>> re.findall(r'[()]|[a-zA-Z]+', s)
['(', '(', '(', 'MY', '(', 'NAME', 'IS', ')', 'IS', ')', 'YOUR', 'NAME', ')']

A non-regex solution using itertools.groupby:

>>> from itertools import groupby
>>> def solve(s):
    for k, g in groupby(s, str.isalpha):
        if k:
            yield ''.join(g)
        else:
            for x in g:
                if not x.isspace():
                    yield x
...                     
>>> list(solve(s))
['(', '(', '(', 'MY', '(', 'NAME', 'IS', ')', 'IS', ')', 'YOUR', 'NAME', ')']
Sign up to request clarification or add additional context in comments.

Comments

0

This should work out.

my_string = "(((MY (NAME IS) IS) YOUR NAME)"
char_list = []

for char in my_string:
    char_list.append(char)

print(char_list)

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

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.