Q:

Calculate the sum and average of the digits present in a string using python programming

0

Calculate the sum and average of the digits present in a string

Given a string s1, write a program to return the sum and average of the digits that appear in the string, ignoring all other characters.

Given:

str1 = "PYnative29@#8496"

Expected Outcome:

Sum is: 38 Average is  6.333333333333333

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Hint:

Iterate each character from a string s1 and check if the current character is digit using the isdigit() function

Solution1:Use string functions

  • Iterate each character from a string s1 using a loop
  • In the body of a loop, check if the current character is digit using the isdigit() function
  • If it is a digit, then add it to the sum variable
  • In the end, calculate the average by dividing the total by the count of digits
input_str = "PYnative29@#8496"
total = 0
cnt = 0
for char in input_str:
    if char.isdigit():
        total += int(char)
        cnt += 1

# average = sum / count of digits
avg = total / cnt
print("Sum is:", total, "Average is ", avg)

Solution2:Use regular expression

import re

input_str = "PYnative29@#8496"
digit_list = [int(num) for num in re.findall(r'\d', input_str)]
print('Digits:', digit_list)

# use the built-in function sum
total = sum(digit_list)

# average = sum / count of digits
avg = total / len(digit_list)
print("Sum is:", total, "Average is ", avg)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now