Python Program to Extract Numbers from String

This article is created to cover some programs in Python, that extract all numbers (0-9) from a given string by user at run-time. Here are the list of programs covered in this article:

Extract Numbers from String using for Loop

The question is, write a Python program to extract numbers from given string using for loop. Here is its answer:

print("Enter the String: ")
text = input()
textLen = len(text)
nums = []
for i in range(textLen):
  if text[i]>='0' and text[i]<='9':
    nums.append(text[i])
print("\nNumbers List in String:")
print(nums)

Here is its sample run:

python extract numbers from string

Now supply the input say 123 this is fresherearth 43 c24o4m as string and press ENTER key to extract all numbers from this string:

extract numbers from string python

Extract Numbers from String using isdigit()

Now this program uses isdigit() method to check whether the current character is a digit (0-9) or not, and then proceed further accordingly. The end in this program is used to skip insertion of an automatic newline.

print(end="Enter the String: ")
text = input()
textLen = len(text)
nums = []
chk = 0
for i in range(textLen):
  if text[i].isdigit():
    nums.append(text[i])
    chk = 1
if chk==1:
  print("\nHere are the list of Numbers in String: ")
  numsLen = len(nums)
  for i in range(numsLen):
    print(end=nums[i] + " ")
else:
  print("\nNumber is not available in the list!")

Here is its sample run with user input, jobails.com123:

extract numbers from string using isdigit python

Here is another sample run with user input, fresherearth (string without number):

get numbers from string python

Python Online Test


« Previous Program Next Program »