Python-courses-python-exercises-python-dictionary

Exercise 29

Write a Python algorithm that determines the list of words containing at least one digit in a given T text.

Solution

# creation of a function which detects if a word contains a number or not
def digitInWord (word):
counter = 0
for x in word:
if x.isdigit ():
counter = counter + 1
if counter> 0:
return True
else:
return False

# creation of a function which returns the list of words containing at least one digit
def digitInText (T):
# initialize the list of words containing at least one digit
listWordWithNumber = []
# convert text T to a list
L = T.split ()
for word in L:
# we test if the word 'word' contains a number
# using the digitInWord function defined previously
if digitInWord (word):
listWordWithNumber.append(word)
return listWordWithNumber
# Example
T = "Python2.7 has been replaced by Python3.X since 2018"
print ("the list of words containing at least one digit is n", digitInText (T))
# the list returned is: ['Python2.7', 'Python3.X', '2018']
Younes Derfoufi
my-courses.net

Leave a Reply