How to split a string of space separated numbers into integers? How to split a string of space separated numbers into integers? arrays arrays

How to split a string of space separated numbers into integers?


Use str.split():

>>> "42 0".split()  # or .split(" ")['42', '0']

Note that str.split(" ") is identical in this case, but would behave differently if there were more than one space in a row. As well, .split() splits on all whitespace, not just spaces.

Using map usually looks cleaner than using list comprehensions when you want to convert the items of iterables to built-ins like int, float, str, etc. In Python 2:

>>> map(int, "42 0".split())[42, 0]

In Python 3, map will return a lazy object. You can get it into a list with list():

>>> map(int, "42 0".split())<map object at 0x7f92e07f8940>>>> list(map(int, "42 0".split()))[42, 0]


text = "42 0"nums = [int(n) for n in text.split()]


l = (int(x) for x in s.split())

If you are sure there are always two integers you could also do:

a,b = (int(x) for x in s.split())

or if you plan on modifying the array after

l = [int(x) for x in s.split()]