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):
# Check for Float Numbers
if '.' in val:
for digit in val.split('.'):
if str.isdigit(digit):
# Non Float Values
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]
add += int(val[i])
if i == len(val)-1:
if add > 0:
add = 0




Cyber Security Student | CTF Player | Not Really An Author

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

Recommended from Medium

Remote Programming Ladies in 2021 — Why it Makes Sense

Automating Tasks with Python & MacOS Terminal

WebAssembly -Part II.A | Wasm with Rust

Hyper-V VM disaster recovery to Azure

Key Benefits of Upgrading from Oracle EBS to Oracle Cloud Infrastructure

Write your tools: simple JIRA automation

A Guide to Any Upcoming SWE Flatiron Students Approaching their Final Project for Phase 1

From Aspiration to Action: Where to Begin Your Serverless Cloud Adoption

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Akshat Soni

Akshat Soni

Cyber Security Student | CTF Player | Not Really An Author

More from Medium

Python, the developer-oriented programming language

How to Print Alphabet W in Python?

How did the shift key get into string of uppercase letters?

Understanding Lists in Python and Numpy Array Shapes