Joseph Wong
Joseph Wong

Reputation: 83

How to split a string with more than one delimiter in python?

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?

Upvotes: 0

Views: 154

Answers (2)

artMart
artMart

Reputation: 11

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)

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250891

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

Upvotes: 7

Related Questions