Home > Software engineering >  creating a function to extract numbers from a list of strings
creating a function to extract numbers from a list of strings

Time:01-17

I need to create a function that takes in a list and only extracts the numbers from that string and this is what I have now.

list00 = ["90", "hello", "55", "Hi", "100"]


def abc(list):
    list_of_numbers = []
    for i in list:
        try:
            list_of_numbers.append(int(i[0]))
        except ValueError:
            pass

print(abc(list00))

ideally i am expecting it to print out [90,55,100] but the actual output, was "none" in the terminal. why is this happening and how can i fix it

CodePudding user response:

You forgot to use return list_of_numbers. You can also use a comprehension:

def abc(lst):
    return [int(i) for i in lst if i.isdigit()]

abc(list00)

Output:

[90, 55, 100]

CodePudding user response:

You don't have return in your function. Also i[0] is not good in this context, as it will give you the 0th character from the string, so for 90 you'd get only 9 as an int, not 90...

from typing import List
items = ["90", "hello", "55", "Hi", "100"]


def extract_numbers(items: List[str])->List[int]:
    numbers = []
    for item in items:
        try:
            numbers.append(int(item))
        except Exception:
            print("Skipping an item which cannot be casted to an int!")
    return numbers

numbers = extract_numbers(items)
print(numbers)

Side notes:

  • give variables (and functions) meaningful names
  • use type hints when possible (it will help later on)
  • do not use reserved keywords as names, not ever (e.g. list, dict, tuple etc. is always a bad name)
  • return from a function if you need its output
  • in general do NOT silently pass on exception, do some logging or at least a print

As for "why was the actual output none": By default function with no explicit return statement (or with return, but no variable returned) returns None. Give it a try:

def foo():pass

x = foo()
print(x) # It's gonna be None

def bar():
    return

y = bar()
print(y) # The same here

  • Related