2

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.")
''

''

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
April
  • 213
  • 1
  • 3
  • 15
  • 1
    You should not use `return`, either store the elements in a list and later return the whole list or use `print` instead of `return` – ZdaR Jun 08 '15 at 14:12
  • 1
    `return` ends execution of the function immediately. Take that into account and rethink your program logic. Don't use the code in the answers if you want to learn... – alexis Jun 08 '15 at 14:25

7 Answers7

4

The whole thing could be replaced by a generator expression:

def allNumbers(string):
    return ''.join(x for x in string if x.isdigit())
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
1

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

0xc0de
  • 8,028
  • 5
  • 49
  • 75
1

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)
Avión
  • 7,963
  • 11
  • 64
  • 105
1

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 []

Pynchia
  • 10,996
  • 5
  • 34
  • 43
  • Why do you use `re.compile(r'\d+')` rather than `re.compile('\d+')` ? – usernumber Jun 16 '20 at 15:14
  • It indicates the string is [raw](https://stackoverflow.com/questions/2081640/what-exactly-do-u-and-r-string-flags-do-and-what-are-raw-string-literals), i.e. not to be escaped – Pynchia Jun 16 '20 at 22:30
1
#!/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
Alex Ivanov
  • 695
  • 4
  • 6
1

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
matino
  • 17,199
  • 8
  • 49
  • 58
1

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'
Joe T. Boka
  • 6,554
  • 6
  • 29
  • 48