Reputation: 83
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
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
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