Home > Back-end >  Convert list of tuple string to list of tuple object in python
Convert list of tuple string to list of tuple object in python

Time:11-21

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

CodePudding user response:

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

CodePudding user response:

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')]
  • Related