Extract Numbers from a String — Python

Hey Everyone! So I was searching for some random problem-solving questions and came across this interesting problem. After spending some time solving this, I came up with this solution and thought to share it with you guys as I didn’t find any proper solution for this problem.

Problem Statement: For a given string, Find the numbers present inside the string and return the count of them. [Sorry don’t remember the exact statement so made this up]

Sample Test Case:


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.

Solution Code:

# Note: We only have to extract complete numbers, Float numbers will be considered as 2 different complete numbers

Hope you guys like the solution and please do suggest if you have some better solution to this problem. THANK YOU for taking the time to read.

Cyber Security Student | CTF Player | Not Really An Author