Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to extract integers from a string in which integers are separated by blank spaces i.e ' '. How could I do that ??

Input

I='1 15 163 132'

Result:

[1,15,163,132]

So I wrote a function which goes like this

def getIt(aStr):
collect = []
i=0
while i < len(aStr):
    print('i = ' + str(i))
    if aStr[i]!=' ':
        j=0
        while aStr[i+j]!=' ' or  (i+j)<=len(aStr)-1:
            print('j = '+str(j))
            j+=1
        if i+j==len(aStr):    
            collect.append(int(aStr[i:i+j-1]))
        else:
            collect.append(int(aStr[i:i+j]))
        i+=j+1

    else:
        i+=1  
return collect

The code runs perfectly when I remove the condition

while aStr[i+j]!=' ':# or  (i+j)<=len(aStr)-1:

And place a blank space at the end of every input string. Please inform where am I going wrong?

like image 359
Akash Singh Avatar asked Feb 05 '15 06:02

Akash Singh


People also ask

How do you take input of integers separated by space in Python?

Use an input() function to accept the list elements from a user in the format of a string separated by space. Next, use a split() function to split an input string by space. The split() method splits a string into a list.

How do you extract an integer from a string in Python?

To find numbers from a given string in Python we can easily apply the isdigit() method. In Python the isdigit() method returns True if all the digit characters contain in the input string and this function extracts the digits from the string. If no character is a digit in the given string then it will return False.

How do you input integers separated by space?

scanf uses any whitespace as a delimiter, so if you just say scanf("%d", &var) it will skip any whitespace and then read an integer (digits up to the next non-digit) and nothing more. Note that whitespace is any whitespace -- spaces, tabs, newlines, or carriage returns.

How to split a string by space in Python?

We shall then split the string by space using String.split () method. split () method returns list of chunks. In this example, we will take a string with chunks separated by one or more single space characters. Then we shall split the string using re.split () function. re.split () returns chunks in a list.

How to extract only integers from a string in Python?

To extract only integers from a string in which words are separated by space character − >>> str1='h3110 23 cat 444.4 rabbit 11 2 dog' >>> for s in str1.split (): if s.isdigit (): print ( (s)) 23 11 2

How to get the digit out of a string in Python?

This problem can be solved by using split function to convert string to list and then the list comprehension which can help us iterating through the list and isdigit function helps to get the digit out of a string. Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

How do I make a list of integers in Python?

The most simple solution is to use .split () to create a list of strings: Alternatively, you can use a list comprehension in combination with the .split () method: This will create a list of int 's if you want integers. Note: map () only returns a list in Python 2.


2 Answers

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.

like image 98
ronrest Avatar answered Oct 10 '22 21:10

ronrest


You could simply do like this,

>>> import re
>>> I='bar 1 15 foo 163 132 foo bar'
>>> [int(i) for i in I.split() if re.match(r'^\d+$', i)]
[1, 15, 163, 132]

Without regex:

>>> I='bar 1 15 foo 163 132 foo bar'
>>> [int(i) for i in I.split() if i.isdigit()]
[1, 15, 163, 132]

i.isdigit() returns true only for the strings which contain only digits.

like image 45
Avinash Raj Avatar answered Oct 10 '22 23:10

Avinash Raj