rofls
rofls

Reputation: 5115

Filtering text in python for numeric values

I know I could use regular expressions to filter text in python for digits, but is that the best way?

Say I have a list of strings:

a="gamma function: 78"
b="factorial value: 120"
c="random number: 33"

is there a good function that would do the following?

for string in [a,b,c]:
    return numbers(string)
78
120
33

Upvotes: 1

Views: 7290

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

Yes, I'd say regexes are the ideal tool for this:

def numbers(s):
    return int(re.search(r"\d+", s).group(0))

For strings with more than one number:

def numbers(s):
    return [int(match) for match in re.findall(r"\d+", s)]

or even

def numbers(s):
    return (int(match) for match in re.finditer(r"\d+", s))

If you want to join all the digits in your string into a single number:

def numbers(s):
    return int("".join(re.findall(r"\d+", s)))

>>> numbers("abc78def90ghi")
7890

Upvotes: 10

jsbueno
jsbueno

Reputation: 110248

Just filter out the non-digits in a generator-expression:

a="gamma function: 78"
b="factorial value: 120"
c="random number: 33"

numbers = []
for string in [a,b,c,]:
    numbers.append( int("".join(char for char in string if char.isdigit())))

Pasting this on the console, I got:

>>> numbers
[78, 120, 33]

Upvotes: 0

Related Questions