Py学习  »  Python

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

Big geez • 6 年前 • 1906 次点击  

我有一根绳子 'Predicate(big,small)'

['Predicate','(','big',',','small',')']

名字可以是任何东西,元素之间也可以有空格,比如so(我需要从列表中去掉空格), Predicate (big, small)

到目前为止我已经试过了,但这显然不是我想要的结果

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

输出:

['P', 'r', 'e', 'd', 'i', 'c', 'a', 't', 'e', '(', 'b', 'i', 'g', ',', 's', 'm', 'a', 'l', 'l', ')']
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55863
文章 [ 2 ]  |  最新文章 6 年前
Ch3steR
Reply   •   1 楼
Ch3steR    6 年前

你可以用 re 在这里。

import re
text='Predicate(big,small)'
parsed=re.findall(r'\w+|[^a-zA-Z,\s])
# ['Predicate', '(', 'big', 'small', ')']
  1. \w+ [a-zA-Z0-9_] ).
  2. [^a-zA-Z,\s] 匹配列表中不存在的单个字符。
  3. \s
Mark Meyer
Reply   •   2 楼
Mark Meyer    6 年前

你可以用 re.split() 拆开你的绳子 ( ) . 您可以捕获regex中的分隔符,以便在最终输出中包含它们。结合 str.strip()

import re

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