Muhammad Taqi
Muhammad Taqi

Reputation: 5424

Convert a String into python list that is already in list format

i have users emails stored in database like this below.

['[email protected]','[email protected]','[email protected]']

I have to get each email of all users one by one. After querying i wrote the following code.

    cur.execute("sql query")
                rows = cur.fetchall()
                for row in rows:
                    print row[2]
                    print type(row[2])
                    emails = json.loads(json.dumps(row[2]))
                    print type(emails)

<type 'str'>
<type 'unicode'>

it converts it into Unicode instead of list.

Upvotes: 0

Views: 82

Answers (1)

unutbu
unutbu

Reputation: 880499

Your row[2] is a string. To convert it to a list you could use ast.literal_eval:

In [29]: text = "['[email protected]','[email protected]','[email protected]']"

In [30]: import ast

In [31]: ast.literal_eval(text)
Out[31]: ['[email protected]', '[email protected]', '[email protected]']

In [32]: type(ast.literal_eval(text))
Out[32]: list

Upvotes: 2

Related Questions