How to extract integers from a string separated by spaces in Python 2.7?

Try this code:

myIntegers = [int(x) for x in I.split()]    

EXPLANATION:


Where s is the string you want to split up, and a is the string you want to use as the delimeter. Then:

s.Split(a)

Splits the string s, at those points where a occurs, and returns a list of sub-strings that have been split up.

If no argument is provided, eg: s.Split() then it defaults to using whitespaces (such as spaces, tabs, newlines) as the delimeter.

Concretely, In your case:

I = '1 15 163 132'
I = I.split() 
print(I)

["1", "15", "163", "132"]

It creates a list of strings, separating at those points where there is a space in your particular example.

Here is the official python documentation on the string split() method.


Now we use what is known as List Comprehensions to convert every element in a list into an integer.

myNewList = [operation for x in myOtherList]

Here is a breakdown of what it is doing:

  • Assuming that myOtherList is a list, with some number of elements,
  • then we will temporarily store one element at a time as x
  • and we will perform some operation for each element in myOtherList
  • assuming that this operation we perform has some return value,
    • then the returned value will be stored as an element in a new list that we are creating
  • The end result is that we will populate a new list myNewList, that is the exact same length as myOtherList

Concretely, In your case:

myIntegers = [int(x) for x in I.split()]    

Performs the following:

  • We saw that I.split() returns ["1", "15", "163", "132"]
  • for each of these string elements, simply convert them to an integer
  • and store that integer as an element in a new list.

See the official python documentation on List Comprehensions for more information.

Hope this helps you.