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]
To convert string to list in Python, use the string split() method. The split() is a built-in Python method that splits the strings and stores them in the list.
Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.
One of these methods uses split() function while other methods convert the string into a list without split() function. Python list has a constructor which accepts an iterable as argument and returns a list whose elements are the elements of iterable. An iterable is a structure that can be iterated.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With