said serty
said serty

Reputation: 3

Split a string in Python with ) and space after

I have a string like that :

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

I need to split it like this :

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

I tried to split it by space but it splits the inner string of comp1 comp2...

Upvotes: 0

Views: 127

Answers (3)

jaap3
jaap3

Reputation: 2846

You could split on ') ' and then add the ')' back in like this:

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)']

It's a bit ugly but it works.

Upvotes: 0

sundar nataraj
sundar nataraj

Reputation: 8702

simply you can Try this way

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)']

or you can use regular expression

Upvotes: 0

GP89
GP89

Reputation: 6730

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)']

Upvotes: 3

Related Questions