用Python分隔一个字符串,然后用空格分割

时间:2014-09-22 10:03:54

标签: python jython

我有一个这样的字符串:

'srv1(compA1 compA2) srv2(compA3 compA2) srv3(comp4 comp5)'

我需要像这样分开它:

['srv1(compA1 compA2)', 'srv2(compA3 compA2)', 'srv3(comp4 comp5)' ]

我试图用空格分割它,但它拆分comp1 comp2的内部字符串......

3 个答案:

答案 0 :(得分:3)

In [9]: import re

In [10]: string = 'srv1(compA1 compA2) srv2(compA3 compA2) srv3(comp4 comp5)'

In [11]: re.split(r'(?<=\)) ', string)
Out[11]: ['srv1(compA1 compA2)', 'srv2(compA3 compA2)', 'srv3(comp4 comp5)']

答案 1 :(得分:0)

只需你可以尝试这种方式

a='srv1(compA1 compA2) srv2(compA3 compA2) srv3(comp4 comp5)'
print a.replace(' s','###s').split('###')

#output
['srv1(compA1 compA2)', 'srv2(compA3 compA2)', 'srv3(comp4 comp5)']

或者您可以使用regular expression

答案 2 :(得分:0)

你可以拆分')',然后像这样添加')':

line = 'srv1(compA1 compA2) srv2(compA3 compA2) srv3(comp4 comp5)'
[e if e.endswith(')') else e + ')' for e in line.split(') ')]
['srv1(compA1 compA2)', 'srv2(compA3 compA2)', 'srv3(comp4 comp5)']

它有点难看,但它有效。