# Extract Numbers from a String — Python

`string = "Th1s i5 a string with 50m3 numb3r5"`
`Count: 6[1, 5, 50 3, 3, 5]`
1. First split up the words from the given string.
2. Scan every word and check if that word is a digit itself [Example: 123].
3. If not, then scan its characters to determine if there is any number within that word.
4. To get the number we will check the ASCII code of the character.
5. If the character is a number then we will add it to an integer variable names ‘add’. Else, we will push the number to the array and reset the ‘add’ s value.
6. For the last iteration, we will check if there is any number there in ‘add’ to push it to the array.
7. For the final output, print the count and the ‘numbers’ array.
`# Note: We only have to extract complete numbers, Float numbers will be considered as 2 different complete numbersstring = "I will eat 2 burgers 2345 fries & 1.25 cokes l8r9 aa"numbers = []for val in string.split(" "):    if str.isdigit(val):        numbers.append(val)    else:        # Check for Float Numbers        if '.' in val:             for digit in val.split('.'):                if str.isdigit(digit):                    numbers.append(digit)        # Non Float Values        else:             add = 0            # Check every character inside string            for i in range(len(val)):                 # Consecutive Numbers                if ord(val[i]) in range(48, 58):                     if add > 0:                        add = (add*10) + int(val[i])                    # Numbers mixed with character [a2bc3]                    else:                         add += int(val[i])                    if i == len(val)-1:                         numbers.append(add)                else:                    if add > 0:                        numbers.append(add)                    add = 0print(len(numbers))print(numbers)`

--

--

--

## More from Akshat Soni

Cyber Security Student | CTF Player | Not Really An Author

Love podcasts or audiobooks? Learn on the go with our new app.

## Akshat Soni

Cyber Security Student | CTF Player | Not Really An Author