简体   繁体   English

如何将以下 Python 字符串拆分为字符串列表?

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

I have a string 'Predicate(big,small)'我有一个字符串'Predicate(big,small)'

How do I derive the following list of strings from that, ['Predicate','(','big',',','small',')']我如何从中得出以下字符串列表, ['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)名称可能是任何东西,元素之间也可以有空格(我需要从列表中取出空格)、 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 ) .您可以使用re.split()()上拆分字符串。 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:结合str.strip()处理空格并过滤掉任何结尾的空字符串,您会得到类似的结果:

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.你可以在这里使用re

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_] ). \\w+匹配任何单词字符(等于[a-zA-Z0-9_] )。
  2. [^a-zA-Z,\\s] matches a single character not present in the list. [^a-zA-Z,\\s]匹配列表中不存在的单个字符。
  3. \\s for matching space. \\s用于匹配空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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