简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM