Is there a better way to extract numbers from a string in python 3

Viewed 2026

I have strings of the form "V70N-HN" and I just need to get the 70 out. The first characters can be any number of letters, or none at all. Same goes for the final characters. I've used variations of this in the past, but it looked cleaner in python 2 without the 'join' and 'list' thrown in the mix:

>>> a = "V70N-HN"
>>> i = int(''.join(list(filter(lambda x: x.isdigit(), a))))
>>> i
70

Anyways, this is not very pythonic anymore. Is there an easier, more understandable way to achieve the same result?

3 Answers

Here's one way you can do the regex search that @Barmar suggested:

>>> import re
>>> int(re.search("\d+", "V70N-HN")[0])
70

Without regex:

>>> int(''.join(filter(str.isdigit, a)))
70

Here's another way using list comprehension:

>>> int(''.join([i for i in a if i.isdigit()]))
70
Related