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.