Converting a String to List in Python


I'm trying to create a list from arguments I receive in a url.

e.g I have:,1,2

Now when I receive it in the request it comes as a string. I want to make a list out of "0,1,2" [0,1,2]

11/15/2011 9:02:09 PM

Accepted Answer

Use the split method. Example:

>>> "0,1,2".split(",")
['0', '1', '2']

Or even,

>>> [int(x) for x in "0,1,2".split(",")]
[0, 1, 2]
1/30/2010 2:16:10 PM

This question was originally tagged Django, so I'll proceed with that in mind.

Inside your view function, the request object has a GET attribute that is an instance of a QueryDict. If you always know that you are going to get a comma separated list of integers for the key "users", you could do something like this in your view function:

users_list = request.GET('users', "").split(',')

That will give you a list of strings, or an empty list if "users" wasn't supplied in GET. If you wanted a list of integers you could process it further with a list comprehension:

users_list = [int(x) for x in users_list]

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow