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

I have a list of thousands of form elements, for example:

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

I am trying to convert these string elements to tuples with ast.literal_eval , but it breaks down, encountering things like leading zeros (like in the third line of the string), with SyntaxError: invalid token error.

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

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

+6
source share
2 answers

Use the 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 remove leading zeros. \b matches between a word character and a non-word character, or vice versa, so there must be a word boundary before zero and after the space character or ( .

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)] 
+4
source

No need to use ast.literal_eval or re . Just divide the parentheses and force them into integers:

 def tupleize(s): s = s.strip('()').split(',') return tuple(int(entry) for entry in s) pixels = [tupleize(pixel) for pixel in pixels] 
+4
source

Source: https://habr.com/ru/post/989635/


All Articles