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?
Use
re
module.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: