2024-10-01 22:31:38 发布
网友
如果我有一个可能是:
'Hello (Test1 test2) (Hello1 hello2) other_stuff'
我想把它分成这样:
然后我将把它放入一个变量中:
full_split=[split1, split2, split3, split4]
而且,未知字符串将是如果他们继续在末尾添加单词,它将继续添加一个拆分变量(split5,split6)
split5
split6
我不喜欢用python来导入。如果有必要,我会的。在
使用regex、str.split和{}:
regex
str.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模块。你可以这样做:
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
使用}:
regex
、str.split
和{标准库中有一个
re
模块。你可以这样做:实际上,这在很大程度上取决于您的输入是什么样子的(空格?其他括号?),所以您可能需要根据您的情况调整它。在
这是有效的,删除空字符串
相关问题 更多 >
编程相关推荐