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:
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:
Now supply the input say 123 this is codescracker 43 c24o4m as string and press
ENTER key to extract all numbers from this string:
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, codescracker.com123:
Here is another sample run with user input, codescracker (string without number):
© Copyright 2021. All Rights Reserved.