Python-courses-python-exercises-python-list

Exercise 34

Write a Python algorithm as a function which takes a string text T as a parameter and which returns the list of words containing at least two digits. Example: if T = 'Python2.7 is replaced by Python3.X since 2018', the function returns the list ['Python2.7', '2018']

Solution

# creation of a function which calculates the number of digits on a string
def number_digit (s):
# initialization of the number of digits
nbrDigit = 0
for x in s:
if x.isdigit():
nbrDigit = nbrDigit + 1
return nbrDigit

# creation of the function which returns the list of words containing at least two digits
def list2Digits(s):
# initialization of the searched words list
listWord = []
# convert string s to a list
L = s.split ()
for word in L:
if number_digit(word) >= 2:
listWord.append (word)
return listWord

# Example
T = "Python2.7 has been replaced by Python3.X since 2018"
print (list2Digits(T)) # prints: ['Python2.7', '2018']
Younes Derfoufi
my-courses.net

Leave a Reply