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:
- We creates an empty list called nums: to store the numeric characters found in the input string.
- It then iterates: over each character in the string s and checks if the character is numeric using the isdigit() method.
- If the character is numeric: it's converted to an integer using the int() method and appended to the nums list.
- Finally: the function returns the nums list containing all the numeric characters found in the input string.
- 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
[…] Exercise 50 || Solution […]