How do I split up the following Python string in to a list of strings?

Viewed 69

I have a string 'Predicate(big,small)'

How do I derive the following list of strings from that, ['Predicate','(','big',',','small',')']

The names can potentially be anything, and there can also be spaces between elements like so (I need to have the whitespace taken out of the list), Predicate (big, small)

So far I've tried this, but this is clearly not the result that I want

>>> str1 = 'Predicate(big,small)'
>>> list(map(str,str1))

Output:

['P', 'r', 'e', 'd', 'i', 'c', 'a', 't', 'e', '(', 'b', 'i', 'g', ',', 's', 'm', 'a', 'l', 'l', ')']
2 Answers

You can use re.split() to split your string on ( or ). You can capture the delimiters in the regex to include them in your final output. Combined with str.strip() to handle spaces and filtering out any ending empty strings you get something like:

import re

s = 'Predicate ( big ,small )'
[s.strip() for s in  re.split(r'([\(\),])', s.strip()) if s]
# ['Predicate', '(', 'big', ',', 'small', ')']

You can use re here.

import re
text='Predicate(big,small)'
parsed=re.findall(r'\w+|[^a-zA-Z,\s])
# ['Predicate', '(', 'big', 'small', ')']
  1. \w+ matches any word character (equal to [a-zA-Z0-9_]).
  2. [^a-zA-Z,\s] matches a single character not present in the list.
  3. \s for matching space.
Related