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