擅长:python、mysql、java
<p>注意,您可以使用内置函数轻松解决此问题。这是一个更为惯用和有效的解决方案:</p>
<pre><code>def sum_digits(digit):
return sum(int(x) for x in digit if x.isdigit())
sum_digits('hihello153john')
=> 9
</code></pre>
<p>尤其要注意,对于字符串类型,<code>is_a_digit()</code>方法已经存在,它被称为<a href="http://docs.python.org/2/library/stdtypes.html#str.isdigit" rel="noreferrer">^{<cd2>}</a>。</p>
<p>使用生成器表达式作为内置函数的参数,可以更简洁地表达<code>sum_digits()</code>函数中的整个循环,如上图所示。</p>