0

I have the following code but it's returning the digits individually. How to return an exact number that is contained in the string?

def hashnumbers(inputString):
    return [char for char in inputString if char.isdigit()]

print(hashnumbers("super 24 string 4")) 

For the above program, I am getting the output like below:

['2', '4', '4']

and I am expecting something like below:

['24', '4']
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Fusdev
  • 119
  • 1
  • 6

3 Answers3

3

Use regex to extract number from a string

import re

regex = r"\d+"

test_str = ("super str66 74ing\n"
    "super 24 string 4")

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):
    
    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
    
    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1
        
        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
abdulsaboor
  • 678
  • 5
  • 10
1

You can use regular expression to find all the matches, like this:

from re import findall

def hashnumbers(string):
    return findall(r'\d+', string)


hashnumbers("abc123 456def g789h")
Lionel Foxcroft
  • 1,584
  • 3
  • 9
  • 23
0

You could use a regular expression and re.findall(). This will cover cases where numbers are not separated from the rest of the string by spaces:

import re
def hashNumbers(inputString):
    return re.findall("[0-9]+",inputString)

output:

hashNumbers("super 24 string4")      # ['24', '4']
hashNumbers("super 24 string 4-18")  # ['24', '4', '18']

Alternatively, you could convert all the non-numeric characters to spaces and use split() on the result:

def hashNumbers(inputString):
    result = "".join(c if c.isdigit() else " " for c in inputString)
    return result.split()
Alain T.
  • 40,517
  • 4
  • 31
  • 51