Numbers in String-1 in Python

This is a very simple question, you need to find the sum and average of all digits that appear in a string. For example,

# let declare a string
my_str = "This is 10th string in 23rd para"

Now, digits are 1 and 0 from 10 and 2 and 3 from 23. So, the sum will be 1+0+2+3=6 and the average will be 6/4=1.5.

Now, we will write a Python program to find the sum and average of numbers in a string.

Code:

my_str = "This is 10th string in 23rd para"

digits=[]

for i in my_str:
    if i.isdigit():
        digits.append(int(i))

number_of_digits = len(digits)
total_sum = sum(digits)
average = total_sum/number_of_digits

print(total_sum)
print(average)

Output:

Numbers in String-1 in Python | Assignment Expert

Also Read:

Share:

Author: Harry

Hello friends, thanks for visiting my website. I am a Python programmer. I, with some other members, write blogs on this website based on Python and Programming. We are still in the growing phase that's why the website design is not so good and there are many other things that need to be corrected in this website but I hope all these things will happen someday. But, till then we will not stop ourselves from uploading more amazing articles. If you want to join us or have any queries, you can mail me at admin@copyassignment.com Thank you