Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 comes as a string. I want to make a list out of "0,1,2" [0,1,2]

like image 912
Fahim Akhter Avatar asked Jan 30 '10 14:01

Fahim Akhter


People also ask

How do I convert a string to a list in Python?

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.

How do you convert a string to a list of elements?

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.

How do I convert a string to a list without splitting in Python?

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.


1 Answers

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]
like image 86
Dietrich Epp Avatar answered Sep 28 '22 00:09

Dietrich Epp