Numbers in String - 2
Given a string, write a program to return the sum and average of the numbers that appear in the string, ignoring all other characters.
Input
The input will be a single line containing a string.
Output
The output should contain the sum and average of the numbers that appear in the string.
Note: Round the average value to two decimal places.
Explanation
For example, if the given string is "I am 25 years and 10 months old", the numbers are 25, 10. Your code should print the sum of the numbers(35) and the average of the numbers(17.5) in the new line.
Sample Input 1
I am 25 years and 10 months old
Sample Output 1
35
17.5
Sample Input 2
Tech Foundation 35567
Sample Output 2
35567
35567.0
Sample input 3
1time3 %times4
sample output 3
8
2.67
please provide correct output code
# This is a program that prints out the sum and averages of
# numbers found in a string, ignoring all the other characters.
# First, loop through the string splitting on spaces
# Declare an empty list to which the extracted numbers will be appended.
# Check through the list of items to determine the numbers using the re module
import re
def string_scanner():
user_input = str(input("Please key in the string you need scanned: \n"))
print(user_input)
# split the string on spaces
string_items = user_input.split(" ")
numbers = []
# loop through each item also checking for numbers:
for item in string_items:
text = item
result = re.split("\D+", text)
for element in result:
if element.isdigit():
numbers.append(int(element))
total = 0
average = 0
list_length = len(numbers)
for i in numbers:
total += i
average = float(total/list_length)
print(total)
print(average)
string_scanner()
Comments
Leave a comment