Reputation: 549
given a string :
>>> string = "0,1,2"
>>> print string
0,1,2
how can I split the string and cast the values into integers, putting them into a list?
Upvotes: 2
Views: 83
Reputation: 8335
Using split,map and int
map produces a list by applying the given function(int as of now) on the given iterable
Code:
string = "0,1,2"
lst = string.split(",")
int_lst = map(int, lst)
print int_lst
Output:
[0, 1, 2]
Upvotes: 1
Reputation: 11585
You can use map
to map the cast to int
to every element of the list you create when splitting it.
>>> string = "0,1,2"
>>> print map(int, string.split(','))
[0, 1, 2]
Upvotes: 1
Reputation: 8386
mystring = "0,1,2"
mylist = [int(i) for i in mystring.split(",")]
print mylist
Output:
[1,2,3]
Upvotes: 2
Reputation: 14169
Just use split
, int
, and a simple list comprehension.
In [1]: s = "0,1,2"
In [2]: t = s.split(",")
In [3]: t
Out[3]: ['0', '1', '2']
In [4]: v = [int(u) for u in t]
In [5]: v
Out[5]: [0, 1, 2]
In one go:
In [7]: v = [int(u) for u in s.split(",")]; v
Out[7]: [0, 1, 2]
Upvotes: 2