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\'
<
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:
Concretely, In your case:
myIntegers = [int(x) for x in I.split()]
Performs the following:
See the official python documentation on List Comprehensions for more information.
Hope this helps you.
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.
Try the following:-
I='1 15 163 132'
map(int, a.split(' '))
import re
x="1 15 163 132"
print re.findall(r"[+-]?\d+(?:\.\d+)?",x)
If you have only positive integers you can simply do
print re.findall(r"\d+",x)
[1, 15, 163, 132]