How can I evaluate a list of strings as a list of tuples in Python?

371 views Asked by At

I have a list of thousands of elements of a form like the following:

pixels = ['(112, 37, 137, 255)', '(129, 39, 145, 255)', '(125, 036, 138, 255)' ...]

I am trying to convert these string elements to tuples using ast.literal_eval, but it is breaking on encountering things like leading zeros (e.g. in the third tuple string shown) with the error SyntaxError: invalid token.

pixels = [ast.literal_eval(pixel) for pixel in pixels]

What would be a good way to deal with things like this and get this list of strings evaluated as a list of tuples?

2

There are 2 answers

4
Avinash Raj On BEST ANSWER

Use re module.

>>> import re
>>> import ast
>>> pixels = ['(112, 37, 137, 255)', '(129, 39, 145, 255)', '(125, 036, 138, 255)']
>>> [ast.literal_eval(re.sub(r'\b0+', '', pixel)) for pixel in pixels]
[(112, 37, 137, 255), (129, 39, 145, 255), (125, 36, 138, 255)]

re.sub(r'\b0+', '', pixel) helps to remove the leading zeros. \b matches between a word character and a non-word character or vice-versa, so here there must be an word boundary exists before zero and after the space or ( symbol.

Update:

>>> pixels = ['(0, 0, 0, 255)', '(129, 39, 145, 255)', '(125, 036, 138, 255)']
>>> [ast.literal_eval(re.sub(r'\b0+\B', '', pixel)) for pixel in pixels]
[(0, 0, 0, 255), (129, 39, 145, 255), (125, 36, 138, 255)]
1
jme On

No need to use ast.literal_eval or re. Just strip the parentheses and coerce to integers:

def tupleize(s):
    s = s.strip('()').split(',')
    return tuple(int(entry) for entry in s)

pixels = [tupleize(pixel) for pixel in pixels]