How to get integer values from a string in Python?

PythonServer Side ProgrammingProgramming

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 -


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


[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))
Updated on 13-Jun-2020 06:53:22