bob
bob

Reputation: 11

How to ignore a letter while adding the sum of digits in a string?

This function receives as input one string containing digits, letters or special symbols.

The function should return one float number contaning the average calculated considering all the digits in the string. If there are no digits the function should return 0.0.

An example: avgDigs('123a456') should return 3.5

So far I have

def avgDigs (st):  
    count = 0  
    total = 0  
    for i in st:  
        if st.isdigit():  
            count += int(i)  
            total += 1  
    print float(count)/total

How can I ignore letters and only add the digits?

Upvotes: 1

Views: 1446

Answers (3)

tianwei
tianwei

Reputation: 1879

Maybe more pythonic.

import re

def avgDigs(st):
    digits = re.findall("[0-9]", st)
    print reduce(lambda x,y:float(x)+float(y) ,digits,0)/len(digits)

Upvotes: 0

ssm
ssm

Reputation: 5373

You can also just filter out the digits:

In [42]: filter(str.isdigit, '123a456')
Out[42]: '123456'

So, the values can be then directly converted to floats,

In [43]: map(float, filter(str.isdigit, '123a456'))
Out[43]: [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]

And Python provides a funciton for finding the mean:

In [44]: mean(map(float, filter(str.isdigit, '123a456')))
Out[44]: 3.5

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239503

You need to check if the current item in the string is a digit, not the entire string. So you need

if i.isdigit():

instead of

if st.isdigit():

Upvotes: 4

Related Questions