9

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]

2
  • 2
    removed the django tag as it's not really a django question Commented Jan 30, 2010 at 15:00
  • 2
    But Django may have some support for parsing URLs that may be of interest. Commented Jan 30, 2010 at 18:21

7 Answers 7

31

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]
Sign up to request clarification or add additional context in comments.

Comments

7

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]

Comments

3
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(','))

Comments

2

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]

1 Comment

I'm just guessing, as I haven't used the framework, but I'd imagine Django wouldn't make him parse the entire query string himself, no?
2

To go from "0,1,2" to ['0','1','2'] its just "0,1,2".split(",")

So if you have it in a variable users, then users.split(",") will give you the list.

If you need them as ints instead of strings, it would be [int(x) for x in users.split(',')].

Comments

0

You can use following code:

s = 'user.com/?users=0,1,2'
s.rpartition('?users=')[2].split(',')

Comments

-2

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'>

1 Comment

He definitely asked for something else!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.