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

Viewed 183419

I have a string "42 0" (for example) and need to get an array of the two integers. Can I do a .split on a space?

9 Answers

You can split and ensure the substring is a digit in a single line:

In [1]: [int(i) for i in '1 2 3a'.split() if i.isdigit()]
Out[1]: [1, 2]

Given: text = "42 0"

import re
numlist = re.findall('\d+',text)

print(numlist)

['42', '0']

Use numpy's fromstring:

import numpy as np

np.fromstring("42 0", dtype=int, sep=' ')
>>> array([42,  0])
Related