Python用空格和圆括号拆分未知字符串

2024-10-01 22:31:38 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有一个可能是:

'Hello (Test1 test2) (Hello1 hello2) other_stuff'

我想把它分成这样:

^{pr2}$

然后我将把它放入一个变量中:

full_split=[split1, split2, split3, split4]

而且,未知字符串将是如果他们继续在末尾添加单词,它将继续添加一个拆分变量(split5split6

我不喜欢用python来导入。如果有必要,我会的。在


Tags: 字符串hellofullsplitothertest1test2stuff
3条回答

使用regexstr.split和{}:

>>> import re
>>> strs = "Hello (Test1 test2) (Hello1 hello2) other_stuff"
>>> [", ".join(x.split()) for x in re.split(r'[()]',strs) if x.strip()]
['Hello', 'Test1, test2', 'Hello1, hello2', 'other_stuff']

标准库中有一个re模块。你可以这样做:

>>> s="Hello (Test1 test2) (Hello1 hello2) other_stuff"
>>> re.findall(r'\w+|\(\w+\s+\w+\)', s)
['Hello', '(Test1 test2)', '(Hello1 hello2)', 'other_stuff']

实际上,这在很大程度上取决于您的输入是什么样子的(空格?其他括号?),所以您可能需要根据您的情况调整它。在

这是有效的,删除空字符串

import re, itertools
strs = 'Hello (Test1 test2) (Hello1 hello2) other_stuff'

res1 = [y for y in re.split(r'\(([^\(]*)\)', strs) if y <> ' ']
print res1     

相关问题 更多 >

    热门问题