简体   繁体   中英

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

i have users emails stored in database like this below.

['abc@gmai.com','abc@gmail.com','abc@gmail.com']

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.

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

In [29]: text = "['abc@gmai.com','abc@gmail.com','abc@gmail.com']"

In [30]: import ast

In [31]: ast.literal_eval(text)
Out[31]: ['abc@gmai.com', 'abc@gmail.com', 'abc@gmail.com']

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM