Reputation: 213
I have a list, that looks like this in python:
ex = ['(1..3),(5..8)']
I need to get out the list like this:
[(1, 3), (5, 8)]
I tried using the replace function, but could only get like
['(1, 3), (5,8)']
and could not lose the '
marks.
Hope someone can help me.
Thanks
Upvotes: 2
Views: 300
Reputation: 43235
if your format is constant, this should work :
>>> n = list(eval(ex[0].replace("..",",")))
>>> n
[(1, 3), (5, 8)]
UPDATE : using literal eval ( safer ):
import ast
result = list(ast.literal_eval(ex[0].replace("..",",")))
Upvotes: 1
Reputation: 212835
import ast
ex = ['(1..3),(5..8)']
list(ast.literal_eval(ex[0].replace('..', ',')))
# returns [(1, 3), (5, 8)]
ast.literal_eval
is safe. eval
is not.
For your updated question:
ex2 = ['(2..5)', '(7..10)']
[ast.literal_eval(a.replace('..', ',')) for a in ex2]
# returns [(2, 5), (7, 10)]
Upvotes: 8
Reputation: 61044
This became uglier than I expected:
In [26]: ex = ['(1..22),(3..44)']
In [27]: [tuple([int(i) for i in s.strip('()').split('..')])
for s in ex[0].split(',')]
Out[27]: [(1, 22), (3, 44)]
Upvotes: 2