# Solution Exercise 62: python program which extract all digit within a given string

Apr 13, 2023

#### Exercise 62

Write a Python algorithm which determines the list of digits within a given string ‘s’. Example: if s = “Python3.8 is more powerful than Python2.7 “ the program must returns the list : [‘3’, ‘8’, ‘2’, ‘7’]

#### Solution

First method:

```def extract_digits(s):
digits = []
for char in s:
if char.isdigit():
digits.append(char)
return digits

#To use this function, you can call it with a string argument:
s = "Python3.8 is more powerful than Python2.7"
digits = extract_digits(s)
print(digits) # Outputs ['3', '8', '2', '7']```

Second method: by using the regular expression
You can use a regular expression to extract all the digits from the string, and then convert them to a list. Here’s the Python program that does this:

```import re

def extract_digits(s):
digit_pattern = re.compile(r'\d')
digits = digit_pattern.findall(s)
return digits

# To use this function, you can call it with a string argument:
s = "Python3.8 is more powerful than Python2.7"
digits = extract_digits(s)
print(digits) # Outputs ['3', '8', '2', '7']```

Younes Derfoufi
my-courses.net