Exercise50

Write a python algorithm as a function which takes a string 's' as input and returns the list of numeric characters contained in the string s. Example if s = 'Python 3.0, released in 2008, and completely revised in 2020' the function returns the list: [3, 0, 2, 0, 0, 8, 2, 0, 2, 0].

Solution

def extract_numerics(s):
    nums = []
    for char in s:
        if char.isdigit():
            nums.append(int(char))
    return nums

s = 'Python 3.0, released in 2008, and completely revised in 2020'
nums = extract_numerics(s)
print(nums)  # Output: [3, 0, 2, 0, 0, 8, 2, 0, 2, 0]





Explanation:

  1. We creates an empty list called nums: to store the numeric characters found in the input string.
  2. It then iterates: over each character in the string s and checks if the character is numeric using the isdigit() method.
  3. If the character is numeric: it's converted to an integer using the int() method and appended to the nums list.
  4. Finally: the function returns the nums list containing all the numeric characters found in the input string.
  5. The output: of this program will be the list [3, 0, 2, 0, 0, 8, 2, 0, 2, 0], which contains all the numeric characters found in the input string.

 

Younes Derfoufi
my-courses.net

One thought on “Solution Exercise 50: python algorithm that extract all numerical character from given string”

Leave a Reply