find and print all numbers in a string in python

2.3k Views Asked by At

I need to make a code with a FOR loop that will find all numbers in a string and then print out all the numbers. So far I have only been able to get the code to print out the first number that is found can you help me pleas?

here is my code:

def allNumbers(string):
 for numbers in string:
    if numbers.isdigit():
        return numbers

When the program is run it should look something like this:

>>> allNumbers("H3llO, H0W 4R3 y0U")
'300430'
>>> allNumbers("Good morning.")
''

''

7

There are 7 best solutions below

0
On
#!/usr/bin/python
# -*- coding: utf-8 -*-

s="H3ll0, H0W 4R3 y0U"
result=''
for char in s:
    try:
        number=int(char)
        print number
        result=result+char
    except:
        pass

print 'Result:', result

Output

3
0
0
4
3
0
Result: 300430
0
On

Solution that will work with digits > 9 and doesn't use regular expressions:

def allnumbers(s):
    i = 0
    end = len(s)
    numbers = []
    while i < end:
        if s[i].isdigit():
            number = ''
            while i < end and s[i].isdigit():
                number += s[i]
                i += 1
            numbers.append(int(number))
        else:
            i += 1
    return numbers
0
On

This is an other way to do it:

>>> a = 'ad56k34kl56'
>>> x = [i for i in a if i.isdigit()]
>>> ','.join(x)

Output:

'5,6,3,4,5,6'
0
On

Instead of returning the number from your function, just insert it into a list.

def allNumbers(string, container=None):
  if not container:
    container = []
  for item in string:
    if item.isdigit():
      container.append(item)
  return container

A better solution:

def allNumbers(orig_str):
  return ''.join(filter(orig_str, str.isdigit))

Yeah it was lame I could think of oneliners only after @Daniels answer :P

0
On

The whole thing could be replaced by a generator expression:

def allNumbers(string):
    return ''.join(x for x in string if x.isdigit())
0
On

You can use a list. And then return it as your desired output.

def allNumbers(string):
    l = []
    for numbers in string:
        if numbers.isdigit():
            l.append(numbers)
    return ''.join(l)
2
On

If I am not mistaken, you have asked for whole numbers, not for each digit in the string. If that is the case, this gives you all the occurrences of separate integer numbers in the string:

import re
def allNumbers(string):
    regex = re.compile(r'\d+')
    return regex.findall(string)

For example:

s = "123 sun 321 moon 34"
for num in allNumbers(s):
    print num

outputs:

123
321
34

N.B.: the output is a list of strings. Cast each element to an integer if you need a number.

If the input string contains floats (e.g. 30.21), then their integer and decimal parts are interpreted as distinct integers (30 and 21).

If there are no matches, the output is an empty list []