0

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

2
  • NameError: name 'apple' is not defined. getting error like this while using eval @LucasM.Uriarte Commented Nov 21, 2022 at 10:45
  • @preRexx you are correct Commented Nov 21, 2022 at 10:54

2 Answers 2

2

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')]
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.