Search code examples
pythonstringlistextractstrip

How can extract numbers from a string to a list as individual elements in python?


I would like to extract the numbers from the below string element of a list of n length into a list in their original form:

list = ['25 birds, 1 cat, 4 dogs, 101 ants']

output = [25, 1, 4, 101]

I'm quite new to regex so I've been trying with the following:

[regex.findall("\d", list[i]) for i in range(len(list))]

However, the output is:

output = [2, 5, 1, 4, 1, 0, 1]

Solution

  • You're missing a +

    you find all should have "\d+", not just "\d"