In: Computer Science
PYTHON 3:
must use try/except for exception handling
Write a function extractInt() that takes a string as a parameter and returns an integer constructed out of the digits that appear in the string. The digits in the integer should appear in the same order as the digits in the string. If the string does not contain any digits or an empty string is provided as a parameter, the value 0 should be return.
!/bin/python3
# extractInt function is used to extract digits
# we are iterating string char by char and checking that char is
digit or Not
# if it is digit then we are appending to digits variable
# if length of digits variable is 0 then returning 0 otherwise
digits variable value
def extractInt(line):
digits = ""
for c in range(0, len(line) - 1):
if line[c].isdigit():
digits += str(line[c])
if len(digits) == 0:
return 0
else:
return digits
# Testing extractInt function with different-2 output
val = extractInt('1, 2, 3 ... we have been counting')
print(val)
val = extractInt('Testing 1. Testing12. Testing again!!')
print(val)
val = extractInt('1 2 3 O\'clock, 5 6 7 o\'clock, 8 9 10
o\'clock')
print(val)
val = extractInt('no digits -- how sad!')
print(val)
val = extractInt('')
print(val)
/*************************************output***************************************************/
123
112
1235678910
0
0