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:
Input:
string = "Th1s i5 a string with 50m3 numb3r5"
Output:
Count: 6
[1, 5, 50 3, 3, 5]
Approach:
- First split up the words from the given string.
- Scan every word and check if that word is a digit itself [Example: 123].
- If not, then scan its characters to determine if there is any number within that word.
- To get the number we will check the ASCII code of the character.
- 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.
- For the last iteration, we will check if there is any number there in ‘add’ to push it to the array.
- 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 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)
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.