Tag Archives: list

Convert a string to a list in Python

I use web.py as the framework of a website project. Recently I developed an iPhone app as the client of the website. The app use POST method to send accelerometer data to the website, and when the web.py receive the data:

class sensor:
    def POST(self):
    data = web.data()
    print data

And the data is like this:


However, when I thought it was a list and try to get data[i], I found that it was

data[0] = '['
data[1] = '['
data[2] = '"'

which means, it is a string, not a list.

I searched online for a solution to convert a string to a list, someone suggested we use string = string[1:-1].split(',') or something. It was a lot of dirty work for my example. Finally, I found an elegant solution for this problem:

list_data = eval(data)

Just as simple as this! Now I can type

for entries in list_data:
    print entries

and get


Of course, the entries itself now is a list, too! 😀

Tagged , ,