简体   繁体   中英

Remove ' from 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

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

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

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("..",",")))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM