Convert list of tuple string to list of tuple object in python

Question:

I have string like below:

[(.1, apple), (.2, orange), (.3, banana), (.4, jack), (.5, grape), (.6, mango)]

i need to convert above string to object in python like below:

[('.1', 'apple'), ('.2', 'orange'), ('.3', 'banana'), ('.4', 'jack'), ('.5', 'grape'), ('.6', 'mango')]

is there any efficient way of converting this either by using regex or any other ways?

Thanks in advance

Asked By: prem Rexx

||

Answers:

you can do the following

import re

string = """[(.1, apple), (.2, orange), (.3, banana), (.4, jack), (.5, grape), (.6, mango)]"""
values = [tuple(ele.split(',')) for ele in re.findall(".d, w+", string)]

this outputs

print(values)
>>> [('.1', ' apple'), ('.2', ' orange'), ('.3', ' banana'), ('.4', ' jack'), ('.5', ' grape'), ('.6', ' mango')]
Answered By: Lucas M. Uriarte

Using ast.literal_eval we can try first converting your string to a valid Python list, then convert to an object:

import ast
import re

inp =  "[(.1, apple), (.2, orange), (.3, banana), (.4, jack), (.5, grape), (.6, mango)]"
inp = re.sub(r'([A-Za-z]+)', r"'1'", inp)
object = ast.literal_eval(inp)
print(object)

This prints:

[(0.1, 'apple'), (0.2, 'orange'), (0.3, 'banana'), (0.4, 'jack'), (0.5, 'grape'), (0.6, 'mango')]
Answered By: Tim Biegeleisen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.