I'm trying to create a list from arguments I receive in a url.
e.g I have:
user.com/?users=0,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]
I'm trying to create a list from arguments I receive in a url.
e.g I have:
user.com/?users=0,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]
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]
import ast
x=ast.literal_eval('0,1,2')
print(x)
# (0, 1, 2)
ast.literal_eval is like eval, but completely safe since it restricts the string to literals such as strings, numbers, tuples, lists, dicts, booleans and None.
Another alternative, not yet mentioned, is to use map:
x=map(int,'0,1,2'.split(','))
To convert the string to a list, use split.
To convert the list of strings to a list of integers, use a list comprehension with int.
So putting it all together, it looks something like this:
s = '0,1,2'
l = [int(x) for x in s.split(',')]
Results:
[1, 2, 3]
You have eval to convert string to "real code":
Example:
>>> l = u"[('0','None'),('2','Taxable Goods'),('4','Shipping')]"
>>> type(l)
<type 'unicode'>
>>> t = eval(l)
>>> type(t)
<type 'list'>