[Python] Converting String Type Objects To Correct Types!

2 min read
I was writing custom template tags for one of my Django package. I came across a situation where I had lists in string format. I need to convert them into lists.
temp_str = '[345, 3, 456, 45]'
required_obj = [345, 3, 456, 45]
There are two methods to get this job done.

1. ast.literal_eval:

This can be used to evaluate  strings containing Python values from untrusted sources without parsing values.
import ast

2. json.loads:

This is used to deserialize a string to python object using a conversion table.
import json
These two functions come in handy whenever you want to convert a list of python objects to their correct types. For example, if you have list of python objects like this
obj_list =  ['hello', '3', '3.64', '-1']
You can convert them to their corresponding types using these functions.
def converter(l):
for i in l:
yield json.loads(i)
except ValueError:
yield i
def converter(l):
for i in l:
yield ast.literal_eval(i)
except ValueError:
yield i
They yield a objects of corresponding types
new_obj_list = ['hello', 3, 3.64, -1]
References: Python Docs, Stackoverflow
Tags: objects | python | tech | type conversion

I am Chillar Anand. I daydream a lot and write about the things that interest me here. You can read more about this blog here.

See all articles

RSS Feed for the blog

Edit this page


Comments powered by Disqus