how to split the string wtih brackets?

Question:

I’d like to splitt the below string into something like this
'180-240','0-100','100-200','0-110','200-240','0-120'

a='(180-240,0-100),(100-200,0-110),(200-240,0-120)'
a
'(180-240,0-100),(100-200,0-110),(200-240,0-120)'

After the below split, it is still one element of string, I am expecting to get a lsit with 3 tuples of

['(180-240,0-100','100-200,0-110','200-240,0-120)']

However I got below a list with only one string. Not sure where is the problem? Thanks


b=a.split('(,)')
b
['(180-240,0-100),(100-200,0-110),(200-240,0-120)']
Asked By: roudan

||

Answers:

One of many possible solutions, use re:

import re

a = "(180-240,0-100),(100-200,0-110),(200-240,0-120)"

print(re.findall(r"[^)(,]+", a))

Prints:

['180-240', '0-100', '100-200', '0-110', '200-240', '0-120']
Answered By: Andrej Kesely

A common pattern here would be to use the built-in str.split method:

source = '(180-240,0-100),(100-200,0-110)'
split_up = source.split(',')
cleaned = [v.strip('()') for v in split_up]
Answered By: Jules
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.