Vasilis Skentos
Vasilis Skentos

Reputation: 566

check if string contains number and return the number

I'm using python and I have a string variable foo = " I have 1 kilo of tomatoes " What I want is to check if my string contains an integer (in our case 1 ) and return the specific integer I know I can use the isdigit function like :

def hashnumbers(inputString):
    return any(char.isdigit() for char in inputString)

But it returns true or false and does not store the number . I would appreciate your help . Thank you in advance .

Upvotes: 1

Views: 3569

Answers (2)

Reece Coombes
Reece Coombes

Reputation: 424

Your question is a little unclear, but I've assumed the following:

  • You want your function to return true or false. Not a number
  • You want the function to print any numbers in the string

If that's right, this code should work:

def hashnumbers(inputString):
    num = False
    for i in inputString:
        if i.isdigit():
            num = True
            print(i)
    return num

However, if I've misunderstood what functionality you're looking for, let me know and I'll amend this.

I hope this helps.

Upvotes: 2

azro
azro

Reputation: 54148

  1. List Comprehension : Return the digits

    To return the digits, use a list comprehension with if

    def hashnumbers(inputString):
        return [char for char in inputString if char.isdigit()]
    
    print(hashnumbers("super string"))    # []
    print(hashnumbers("super 2 string"))  # ['2']
    print(hashnumbers("super 2 3 string")) # ['2', '3']
    
  2. Return a default value if no digits found (empty list is evaluated as False)

    return [char for char in inputString if char.isdigit()] or None
    
  3. Regex version with re.findall

    return re.findall(r"\d", inputString) 
    return re.findall(r"\d", inputString) or None
    
  4. Return first one only

    def hashnumbers(inputString):
        return next((char for char in inputString if char.isdigit()), None)
    
    print(hashnumbers("super string"))    # None
    print(hashnumbers("super 2 string"))  # 2
    print(hashnumbers("super 2 3string")) # 2
    

Upvotes: 5

Related Questions