开发者

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:

 user.com/?users=0,1,2

Now when I receive it in the request it come开发者_如何学Cs as a string. I want to make a list out of "0,1,2" [0,1,2]


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]


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]


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


You can use following code:

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜