Sum of digits in a string

前端 未结 8 2043
天涯浪人
天涯浪人 2020-12-06 12:35

if i just read my sum_digits function here, it makes sense in my head but it seems to be producing wrong results. Any tip?

def is_a_digit(s):
\         


        
8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 13:24

    Notice that you can easily solve this problem using built-in functions. This is a more idiomatic and efficient solution:

    def sum_digits(digit):
        return sum(int(x) for x in digit if x.isdigit())
    
    sum_digits('hihello153john')
    => 9
    

    In particular, be aware that the is_a_digit() method already exists for string types, it's called isdigit().

    And the whole loop in the sum_digits() function can be expressed more concisely using a generator expression as a parameter for the sum() built-in function, as shown above.

提交回复
热议问题