Reman Reman - 4 years ago 158
Python Question

How to split up a string using 2 split parameters?

Example:

r="\\%4l\\%(wit.*wit\\)\\|\\%8l\\%(rood.*rood\\)\\|\\%12l\\%(blauw.*blauw\\)\\|\\%13l\\%(wit.*wit\\)\\|\\%14l\\%(blauw.*blauw\\)\\|\\%15l\\%(wit.*wit\\)\\|\\%16l\\%(wit.*wit\\)\\|\\%17l\\%(rood.*rood\\)\\|\\%19l\\%(wit.*wit\\)\\|\\%21l\\%(blauw.*blauw\\)"


I want to split the string to a list, but not using 1 parameter but 2 parameters.


  • First I want to capture the number before
    l\\%(

  • Second I want to capture the text between
    \\%(
    and
    \\)\\|
    or
    in case of the end of the string between
    \\%(
    and
    \\)$



Output:

[[4, "wit.*wit"], [8, "rood.*rood"], [12, "blauw.*blauw"], [13, "wit.*wit"], [14, "blauw.*blauw"], [15, "wit.*wit"], [16,"wit.*wit"], [17, "rood.*rood"], [19, "wit.*wit"], [21, "blauw.*blauw"]]


What I tried is to split the string at
\\|
and than substituting every undesired character with "".

Is there a better way in python to do this?

Answer Source

One way to approach it would be to use re.findall() with two capturing groups to find the desired pairs:

In [3]: re.findall(r"%(\d+)l\\%\((.*?)\\\)", r)
Out[3]: 
[('4', 'wit.*wit'),
 ('8', 'rood.*rood'),
 ('12', 'blauw.*blauw'),
 ('13', 'wit.*wit'),
 ('14', 'blauw.*blauw'),
 ('15', 'wit.*wit'),
 ('16', 'wit.*wit'),
 ('17', 'rood.*rood'),
 ('19', 'wit.*wit'),
 ('21', 'blauw.*blauw')]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download