2

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?

1
  • Thanks to everybody, many correct answers, I'll accept the answer I consider clearer Commented Oct 30, 2015 at 10:32

4 Answers 4

2
mystring = "0,1,2"
mylist = [int(i) for i in mystring.split(",")]
print mylist

Output:

[1,2,3]
Sign up to request clarification or add additional context in comments.

Comments

2

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]

Comments

1

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]

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.