Computer >> Computer tutorials >  >> Programming >> Python

How to get integer values from a string in Python?


You can use regular expressions to get all integer values in order of their occurance in an array. You can use the following code to get those values -

Example

import re
s = "12 hello 52 19 some random 15 number"
# Extract numbers and cast them to int
list_of_nums = map(int, re.findall('\d+', s))
print list_of_nums

Output

[12, 52, 19, 15]

If you want to concatenate all numbers in one number and output that, then you can use str.isdigit method to filter them. For example,

>>> s = "12 hello 52 19 some random 15 number"
>>> print int(filter(str.isdigit, s))
12521915