简体   繁体   中英

Converting a String to List in Python

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

eg 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]

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM