1

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
rofls
  • 4,993
  • 3
  • 27
  • 37

2 Answers2

10

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
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
0

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]
jsbueno
  • 99,910
  • 10
  • 151
  • 209
  • This is good for one number in each string, even if the digits are sparsed by other chars. Please clarify your question if there are cases in which there may be more than one number in each string - oh, i saw that yes, in your comments now. – jsbueno Dec 14 '12 at 21:28