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
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)]
Look like some regex task.
>>> import re
>>> ex = ['(1..3),(5..8)']
>>> re.findall(r'\((\d+)\.\.(\d+)\)', ex[0])
[('1', '3'), ('5', '8')]
>>> # if you want tuple of numbers
... [tuple(map(int, x)) for x in _]
[(1, 3), (5, 8)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With