Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove ' from python list

Tags:

python

list

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

like image 239
X-Pender Avatar asked Jun 22 '26 18:06

X-Pender


2 Answers

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)]
like image 124
eumiro Avatar answered Jun 24 '26 06:06

eumiro


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)]
like image 25
kennytm Avatar answered Jun 24 '26 08:06

kennytm